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 = [
51 public $mMainLanguageCode;
57 public $mVariantFallbacks;
58 public $mVariantNames;
59 public $mTablesLoaded = false;
61 // 'bidirectional' 'unidirectional' 'disable' for each variant
66 public $mDescCodeSep = ':', $mDescVarSep = ';';
67 public $mUcfirst = false;
68 public $mConvRuleTitle = false;
71 public $mHeaderVariant;
72 public $mMaxDepth = 10;
73 public $mVarSeparatorPattern;
75 const CACHE_VERSION_KEY
= 'VERSION 7';
78 * @param Language $langobj
79 * @param string $maincode The main language code of this language
80 * @param string[] $variants The supported variants of this language
81 * @param array $variantfallbacks The fallback language of each variant
82 * @param array $flags Defining the custom strings that maps to the flags
83 * @param array $manualLevel Limit for supported variants
85 public function __construct( $langobj, $maincode, $variants = [],
86 $variantfallbacks = [], $flags = [],
88 global $wgDisabledVariants;
89 $this->mLangObj
= $langobj;
90 $this->mMainLanguageCode
= $maincode;
91 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
92 $this->mVariantFallbacks
= $variantfallbacks;
93 $this->mVariantNames
= Language
::fetchLanguageNames();
95 // 'S' show converted text
96 // '+' add rules for alltext
97 // 'E' the gave flags is error
98 // these flags above are reserved for program
99 'A' => 'A', // add rule for convert code (all text convert)
100 'T' => 'T', // title convert
101 'R' => 'R', // raw content
102 'D' => 'D', // convert description (subclass implement)
103 '-' => '-', // remove convert (not implement)
104 'H' => 'H', // add rule for convert code (but no display in placed code)
105 'N' => 'N', // current variant name
107 $this->mFlags
= array_merge( $defaultflags, $flags );
108 foreach ( $this->mVariants
as $v ) {
109 if ( array_key_exists( $v, $manualLevel ) ) {
110 $this->mManualLevel
[$v] = $manualLevel[$v];
112 $this->mManualLevel
[$v] = 'bidirectional';
114 $this->mFlags
[$v] = $v;
119 * Get all valid variants.
120 * Call this instead of using $this->mVariants directly.
122 * @return string[] Contains all valid variants
124 public function getVariants() {
125 return $this->mVariants
;
129 * In case some variant is not defined in the markup, we need
130 * to have some fallback. For example, in zh, normally people
131 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
132 * when zh-sg is preferred but not defined, we will pick zh-hans
133 * in this case. Right now this is only used by zh.
135 * @param string $variant The language code of the variant
136 * @return string|array The code of the fallback language or the
137 * main code if there is no fallback
139 public function getVariantFallbacks( $variant ) {
140 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
141 return $this->mVariantFallbacks
[$variant];
143 return $this->mMainLanguageCode
;
147 * Get the title produced by the conversion rule.
148 * @return string The converted title text
150 public function getConvRuleTitle() {
151 return $this->mConvRuleTitle
;
155 * Get preferred language variant.
156 * @return string The preferred language code
158 public function getPreferredVariant() {
159 global $wgDefaultLanguageVariant, $wgUser;
161 $req = $this->getURLVariant();
163 if ( $wgUser->isSafeToLoad() && $wgUser->isLoggedIn() && !$req ) {
164 $req = $this->getUserVariant();
166 $req = $this->getHeaderVariant();
169 if ( $wgDefaultLanguageVariant && !$req ) {
170 $req = $this->validateVariant( $wgDefaultLanguageVariant );
173 // This function, unlike the other get*Variant functions, is
174 // not memoized (i.e. there return value is not cached) since
175 // new information might appear during processing after this
177 if ( $this->validateVariant( $req ) ) {
180 return $this->mMainLanguageCode
;
184 * Get default variant.
185 * This function would not be affected by user's settings
186 * @return string The default variant code
188 public function getDefaultVariant() {
189 global $wgDefaultLanguageVariant;
191 $req = $this->getURLVariant();
194 $req = $this->getHeaderVariant();
197 if ( $wgDefaultLanguageVariant && !$req ) {
198 $req = $this->validateVariant( $wgDefaultLanguageVariant );
204 return $this->mMainLanguageCode
;
208 * Validate the variant
209 * @param string $variant The variant to validate
210 * @return mixed Returns the variant if it is valid, null otherwise
212 public function validateVariant( $variant = null ) {
213 if ( $variant !== null && in_array( $variant, $this->mVariants
) ) {
220 * Get the variant specified in the URL
222 * @return mixed Variant if one found, false otherwise.
224 public function getURLVariant() {
227 if ( $this->mURLVariant
) {
228 return $this->mURLVariant
;
231 // see if the preference is set in the request
232 $ret = $wgRequest->getText( 'variant' );
235 $ret = $wgRequest->getVal( 'uselang' );
238 $this->mURLVariant
= $this->validateVariant( $ret );
239 return $this->mURLVariant
;
243 * Determine if the user has a variant set.
245 * @return mixed Variant if one found, false otherwise.
247 protected function getUserVariant() {
248 global $wgUser, $wgContLang;
250 // memoizing this function wreaks havoc on parserTest.php
252 if ( $this->mUserVariant ) {
253 return $this->mUserVariant;
257 // Get language variant preference from logged in users
258 // Don't call this on stub objects because that causes infinite
259 // recursion during initialisation
260 if ( !$wgUser->isSafeToLoad() ) {
263 if ( $wgUser->isLoggedIn() ) {
264 if ( $this->mMainLanguageCode
== $wgContLang->getCode() ) {
265 $ret = $wgUser->getOption( 'variant' );
267 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode
);
270 // figure out user lang without constructing wgLang to avoid
271 // infinite recursion
272 $ret = $wgUser->getOption( 'language' );
275 $this->mUserVariant
= $this->validateVariant( $ret );
276 return $this->mUserVariant
;
280 * Determine the language variant from the Accept-Language header.
282 * @return mixed Variant if one found, false otherwise.
284 protected function getHeaderVariant() {
287 if ( $this->mHeaderVariant
) {
288 return $this->mHeaderVariant
;
291 // see if some supported language variant is set in the
293 $languages = array_keys( $wgRequest->getAcceptLang() );
294 if ( empty( $languages ) ) {
298 $fallbackLanguages = [];
299 foreach ( $languages as $language ) {
300 $this->mHeaderVariant
= $this->validateVariant( $language );
301 if ( $this->mHeaderVariant
) {
305 // To see if there are fallbacks of current language.
306 // We record these fallback variants, and process
308 $fallbacks = $this->getVariantFallbacks( $language );
309 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
310 $fallbackLanguages[] = $fallbacks;
311 } elseif ( is_array( $fallbacks ) ) {
313 array_merge( $fallbackLanguages, $fallbacks );
317 if ( !$this->mHeaderVariant
) {
318 // process fallback languages now
319 $fallback_languages = array_unique( $fallbackLanguages );
320 foreach ( $fallback_languages as $language ) {
321 $this->mHeaderVariant
= $this->validateVariant( $language );
322 if ( $this->mHeaderVariant
) {
328 return $this->mHeaderVariant
;
332 * Dictionary-based conversion.
333 * This function would not parse the conversion rules.
334 * If you want to parse rules, try to use convert() or
337 * @param string $text The text to be converted
338 * @param bool|string $toVariant The target language code
339 * @return string The converted text
341 public function autoConvert( $text, $toVariant = false ) {
345 $toVariant = $this->getPreferredVariant();
351 if ( $this->guessVariant( $text, $toVariant ) ) {
355 /* we convert everything except:
356 * 1. HTML markups (anything between < and >)
358 * 3. placeholders created by the parser
360 $marker = '|' . Parser
::MARKER_PREFIX
. '[\-a-zA-Z0-9]+';
362 // this one is needed when the text is inside an HTML markup
363 $htmlfix = '|<[^>]+$|^[^<>]*>';
365 // disable convert to variants between <code> tags
366 $codefix = '<code>.+?<\/code>|';
367 // disable conversion of <script> tags
368 $scriptfix = '<script.*?>.*?<\/script>|';
369 // disable conversion of <pre> tags
370 $prefix = '<pre.*?>.*?<\/pre>|';
372 $reg = '/' . $codefix . $scriptfix . $prefix .
373 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
378 // Guard against delimiter nulls in the input
379 // (should never happen: see T159174)
380 $text = str_replace( "\000", '', $text );
382 $markupMatches = null;
383 $elementMatches = null;
384 while ( $startPos < strlen( $text ) ) {
385 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
386 $elementPos = $markupMatches[0][1];
387 $element = $markupMatches[0][0];
389 $elementPos = strlen( $text );
393 // Queue the part before the markup for translation in a batch
394 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
396 // Advance to the next position
397 $startPos = $elementPos +
strlen( $element );
399 // Translate any alt or title attributes inside the matched element
401 && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element, $elementMatches )
403 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
405 foreach ( [ 'title', 'alt' ] as $attrName ) {
406 if ( !isset( $attrs[$attrName] ) ) {
409 $attr = $attrs[$attrName];
410 // Don't convert URLs
411 if ( !strpos( $attr, '://' ) ) {
412 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
415 if ( $attr !== $attrs[$attrName] ) {
416 $attrs[$attrName] = $attr;
421 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
425 $literalBlob .= $element . "\000";
428 // Do the main translation batch
429 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
431 // Put the output back together
432 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
433 $literalIter = StringUtils
::explode( "\000", $literalBlob );
435 while ( $translatedIter->valid() && $literalIter->valid() ) {
436 $output .= $translatedIter->current();
437 $output .= $literalIter->current();
438 $translatedIter->next();
439 $literalIter->next();
446 * Translate a string to a variant.
447 * Doesn't parse rules or do any of that other stuff, for that use
448 * convert() or convertTo().
450 * @param string $text Text to convert
451 * @param string $variant Variant language code
452 * @return string Translated text
454 public function translate( $text, $variant ) {
455 // If $text is empty or only includes spaces, do nothing
456 // Otherwise translate it
457 if ( trim( $text ) ) {
459 $text = $this->mTables
[$variant]->replace( $text );
465 * Call translate() to convert text to all valid variants.
467 * @param string $text The text to be converted
468 * @return array Variant => converted text
470 public function autoConvertToAllVariants( $text ) {
474 foreach ( $this->mVariants
as $variant ) {
475 $ret[$variant] = $this->translate( $text, $variant );
482 * Apply manual conversion rules.
484 * @param ConverterRule $convRule
486 protected function applyManualConv( $convRule ) {
487 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
489 // T26072: $mConvRuleTitle was overwritten by other manual
490 // rule(s) not for title, this breaks the title conversion.
491 $newConvRuleTitle = $convRule->getTitle();
492 if ( $newConvRuleTitle ) {
493 // So I add an empty check for getTitle()
494 $this->mConvRuleTitle
= $newConvRuleTitle;
497 // merge/remove manual conversion rules to/from global table
498 $convTable = $convRule->getConvTable();
499 $action = $convRule->getRulesAction();
500 foreach ( $convTable as $variant => $pair ) {
501 if ( !$this->validateVariant( $variant ) ) {
505 if ( $action == 'add' ) {
506 // More efficient than array_merge(), about 2.5 times.
507 foreach ( $pair as $from => $to ) {
508 $this->mTables
[$variant]->setPair( $from, $to );
510 } elseif ( $action == 'remove' ) {
511 $this->mTables
[$variant]->removeArray( $pair );
517 * Auto convert a Title object to a readable string in the
520 * @param Title $title A object of Title
521 * @return string Converted title text
523 public function convertTitle( $title ) {
524 $variant = $this->getPreferredVariant();
525 $index = $title->getNamespace();
526 if ( $index !== NS_MAIN
) {
527 $text = $this->convertNamespace( $index, $variant ) . ':';
531 $text .= $this->translate( $title->getText(), $variant );
536 * Get the namespace display name in the preferred variant.
538 * @param int $index Namespace id
539 * @param string|null $variant Variant code or null for preferred variant
540 * @return string Namespace name for display
542 public function convertNamespace( $index, $variant = null ) {
543 if ( $index === NS_MAIN
) {
547 if ( $variant === null ) {
548 $variant = $this->getPreferredVariant();
551 $cache = MediaWikiServices
::getInstance()->getLocalServerObjectCache();
552 $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
553 $nsVariantText = $cache->get( $key );
554 if ( $nsVariantText !== false ) {
555 return $nsVariantText;
558 // First check if a message gives a converted name in the target variant.
559 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
560 if ( $nsConvMsg->exists() ) {
561 $nsVariantText = $nsConvMsg->plain();
564 // Then check if a message gives a converted name in content language
565 // which needs extra translation to the target variant.
566 if ( $nsVariantText === false ) {
567 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
568 if ( $nsConvMsg->exists() ) {
569 $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
573 if ( $nsVariantText === false ) {
574 // No message exists, retrieve it from the target variant's namespace names.
575 $langObj = $this->mLangObj
->factory( $variant );
576 $nsVariantText = $langObj->getFormattedNsText( $index );
579 $cache->set( $key, $nsVariantText, 60 );
581 return $nsVariantText;
585 * Convert text to different variants of a language. The automatic
586 * conversion is done in autoConvert(). Here we parse the text
587 * marked with -{}-, which specifies special conversions of the
588 * text that can not be accomplished in autoConvert().
590 * Syntax of the markup:
591 * -{code1:text1;code2:text2;...}- or
592 * -{flags|code1:text1;code2:text2;...}- or
593 * -{text}- in which case no conversion should take place for text
595 * @param string $text Text to be converted
596 * @return string Converted text
598 public function convert( $text ) {
599 $variant = $this->getPreferredVariant();
600 return $this->convertTo( $text, $variant );
604 * Same as convert() except a extra parameter to custom variant.
606 * @param string $text Text to be converted
607 * @param string $variant The target variant code
608 * @return string Converted text
610 public function convertTo( $text, $variant ) {
611 global $wgDisableLangConversion;
612 if ( $wgDisableLangConversion ) {
615 // Reset converter state for a new converter run.
616 $this->mConvRuleTitle
= false;
617 return $this->recursiveConvertTopLevel( $text, $variant );
621 * Recursively convert text on the outside. Allow to use nested
622 * markups to custom rules.
624 * @param string $text Text to be converted
625 * @param string $variant The target variant code
626 * @param int $depth Depth of recursion
627 * @return string Converted text
629 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
632 $length = strlen( $text );
633 $shouldConvert = !$this->guessVariant( $text, $variant );
635 while ( $startPos < $length ) {
636 $pos = strpos( $text, '-{', $startPos );
638 if ( $pos === false ) {
639 // No more markup, append final segment
640 $fragment = substr( $text, $startPos );
641 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
646 // Append initial segment
647 $fragment = substr( $text, $startPos, $pos - $startPos );
648 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
653 // Do recursive conversion
654 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
661 * Recursively convert text on the inside.
663 * @param string $text Text to be converted
664 * @param string $variant The target variant code
665 * @param int $startPos
666 * @param int $depth Depth of recursion
668 * @throws MWException
669 * @return string Converted text
671 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
672 // Quick sanity check (no function calls)
673 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
674 throw new MWException( __METHOD__
. ': invalid input string' );
679 $warningDone = false;
680 $length = strlen( $text );
682 while ( $startPos < $length ) {
684 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
694 // Append initial segment
695 $inner .= substr( $text, $startPos, $pos - $startPos );
703 if ( $depth >= $this->mMaxDepth
) {
705 if ( !$warningDone ) {
706 $inner .= '<span class="error">' .
707 wfMessage( 'language-converter-depth-warning' )
708 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
715 // Recursively parse another rule
716 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
721 $rule = new ConverterRule( $inner, $this );
722 $rule->parse( $variant );
723 $this->applyManualConv( $rule );
724 return $rule->getDisplay();
726 throw new MWException( __METHOD__
. ': invalid regex match' );
731 if ( $startPos < $length ) {
732 $inner .= substr( $text, $startPos );
735 return '-{' . $this->autoConvert( $inner, $variant );
739 * If a language supports multiple variants, it is possible that
740 * non-existing link in one variant actually exists in another variant.
741 * This function tries to find it. See e.g. LanguageZh.php
742 * The input parameters may be modified upon return
744 * @param string &$link The name of the link
745 * @param Title &$nt The title object of the link
746 * @param bool $ignoreOtherCond To disable other conditions when
747 * we need to transclude a template or update a category's link
749 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
750 # If the article has already existed, there is no need to
751 # check it again, otherwise it may cause a fault.
752 if ( is_object( $nt ) && $nt->exists() ) {
756 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
757 $isredir = $wgRequest->getText( 'redirect', 'yes' );
758 $action = $wgRequest->getText( 'action' );
759 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
762 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
763 $disableLinkConversion = $wgDisableLangConversion
764 ||
$wgDisableTitleConversion;
765 $linkBatch = new LinkBatch();
769 if ( $disableLinkConversion ||
770 ( !$ignoreOtherCond &&
773 ||
$action == 'submit'
774 ||
$linkconvert == 'no' ) ) ) {
778 if ( is_object( $nt ) ) {
779 $ns = $nt->getNamespace();
782 $variants = $this->autoConvertToAllVariants( $link );
783 if ( !$variants ) { // give up
789 foreach ( $variants as $v ) {
791 $varnt = Title
::newFromText( $v, $ns );
792 if ( !is_null( $varnt ) ) {
793 $linkBatch->addObj( $varnt );
799 // fetch all variants in single query
800 $linkBatch->execute();
802 foreach ( $titles as $varnt ) {
803 if ( $varnt->getArticleID() > 0 ) {
805 $link = $varnt->getText();
812 * Returns language specific hash options.
816 public function getExtraHashOptions() {
817 $variant = $this->getPreferredVariant();
819 return '!' . $variant;
823 * Guess if a text is written in a variant. This should be implemented in subclasses.
825 * @param string $text The text to be checked
826 * @param string $variant Language code of the variant to be checked for
827 * @return bool True if $text appears to be written in $variant, false if not
829 * @author Nikola Smolenski <smolensk@eunet.rs>
832 public function guessVariant( $text, $variant ) {
837 * Load default conversion tables.
838 * This method must be implemented in derived class.
841 * @throws MWException
843 function loadDefaultTables() {
844 $class = static::class;
845 throw new MWException( "Must implement loadDefaultTables() method in class $class" );
849 * Load conversion tables either from the cache or the disk.
851 * @param bool $fromCache Load from memcached? Defaults to true.
853 function loadTables( $fromCache = true ) {
854 global $wgLanguageConverterCacheType;
856 if ( $this->mTablesLoaded
) {
860 $this->mTablesLoaded
= true;
861 $this->mTables
= false;
862 $cache = ObjectCache
::getInstance( $wgLanguageConverterCacheType );
863 $cacheKey = $cache->makeKey( 'conversiontables', $this->mMainLanguageCode
);
865 $this->mTables
= $cache->get( $cacheKey );
867 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
868 // not in cache, or we need a fresh reload.
869 // We will first load the default tables
870 // then update them using things in MediaWiki:Conversiontable/*
871 $this->loadDefaultTables();
872 foreach ( $this->mVariants
as $var ) {
873 $cached = $this->parseCachedTable( $var );
874 $this->mTables
[$var]->mergeArray( $cached );
877 $this->postLoadTables();
878 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
880 $cache->set( $cacheKey, $this->mTables
, 43200 );
885 * Hook for post processing after conversion tables are loaded.
887 function postLoadTables() {
891 * Reload the conversion tables.
893 * Also used by test suites which need to reset the converter state.
897 private function reloadTables() {
898 if ( $this->mTables
) {
899 unset( $this->mTables
);
902 $this->mTablesLoaded
= false;
903 $this->loadTables( false );
907 * Parse the conversion table stored in the cache.
909 * The tables should be in blocks of the following form:
916 * To make the tables more manageable, subpages are allowed
917 * and will be parsed recursively if $recursive == true.
919 * @param string $code Language code
920 * @param string $subpage Subpage name
921 * @param bool $recursive Parse subpages recursively? Defaults to true.
925 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
928 $key = 'Conversiontable/' . $code;
930 $key .= '/' . $subpage;
932 if ( array_key_exists( $key, $parsed ) ) {
936 $parsed[$key] = true;
938 if ( $subpage === '' ) {
939 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
942 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
943 if ( $title && $title->exists() ) {
944 $revision = Revision
::newFromTitle( $title );
946 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
947 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
950 // @todo in the future, use a specialized content model, perhaps based on json!
955 # Nothing to parse if there's no text
956 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
960 // get all subpage links of the form
961 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
962 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
964 $subs = StringUtils
::explode( '[[', $txt );
966 foreach ( $subs as $sub ) {
967 $link = explode( ']]', $sub, 2 );
968 if ( count( $link ) != 2 ) {
971 $b = explode( '|', $link[0], 2 );
972 $b = explode( '/', trim( $b[0] ), 3 );
973 if ( count( $b ) == 3 ) {
979 if ( $b[0] == $linkhead && $b[1] == $code ) {
980 $sublinks[] = $sublink;
984 // parse the mappings in this page
985 $blocks = StringUtils
::explode( '-{', $txt );
988 foreach ( $blocks as $block ) {
990 // Skip the part before the first -{
994 $mappings = explode( '}-', $block, 2 )[0];
995 $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
996 $table = StringUtils
::explode( ';', $stripped );
997 foreach ( $table as $t ) {
998 $m = explode( '=>', $t, 3 );
999 if ( count( $m ) != 2 ) {
1002 // trim any trailling comments starting with '//'
1003 $tt = explode( '//', $m[1], 2 );
1004 $ret[trim( $m[0] )] = trim( $tt[0] );
1008 // recursively parse the subpages
1010 foreach ( $sublinks as $link ) {
1011 $s = $this->parseCachedTable( $code, $link, $recursive );
1016 if ( $this->mUcfirst
) {
1017 foreach ( $ret as $k => $v ) {
1018 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1025 * Enclose a string with the "no conversion" tag. This is used by
1026 * various functions in the Parser.
1028 * @param string $text Text to be tagged for no conversion
1029 * @param bool $noParse Unused
1030 * @return string The tagged text
1032 public function markNoConversion( $text, $noParse = false ) {
1033 # don't mark if already marked
1034 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1038 $ret = "-{R|$text}-";
1043 * Convert the sorting key for category links. This should make different
1044 * keys that are variants of each other map to the same key.
1046 * @param string $key
1050 function convertCategoryKey( $key ) {
1055 * Refresh the cache of conversion tables when
1056 * MediaWiki:Conversiontable* is updated.
1058 * @param Title $titleobj The Title of the page being updated
1060 public function updateConversionTable( Title
$titleobj ) {
1061 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1062 $title = $titleobj->getDBkey();
1063 $t = explode( '/', $title, 3 );
1065 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1066 if ( $this->validateVariant( $t[1] ) ) {
1067 $this->reloadTables();
1074 * Get the cached separator pattern for ConverterRule::parseRules()
1077 function getVarSeparatorPattern() {
1078 if ( is_null( $this->mVarSeparatorPattern
) ) {
1079 // varsep_pattern for preg_split:
1080 // text should be splited by ";" only if a valid variant
1081 // name exist after the markup, for example:
1082 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1083 // <span style="font-size:120%;">yyy</span>;}-
1084 // we should split it as:
1086 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1087 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1091 foreach ( $this->mVariants
as $variant ) {
1092 // zh-hans:xxx;zh-hant:yyy
1093 $pat .= $variant . '\s*:|';
1094 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1095 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1098 $this->mVarSeparatorPattern
= $pat;
1100 return $this->mVarSeparatorPattern
;