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
23 * Base class for language conversion.
26 * @author Zhengzhu Feng <zhengzhu@gmail.com>
27 * @author fdcn <fdcn64@gmail.com>
28 * @author shinjiman <shinjiman@gmail.com>
29 * @author PhiLiP <philip.npc@gmail.com>
31 class LanguageConverter
{
33 * languages supporting variants
37 static public $languagesWithVariants = [
49 public $mMainLanguageCode;
50 public $mVariants, $mVariantFallbacks, $mVariantNames;
51 public $mTablesLoaded = false;
53 // 'bidirectional' 'unidirectional' 'disable' for each variant
57 * @var string Memcached key name
63 public $mDescCodeSep = ':', $mDescVarSep = ';';
64 public $mUcfirst = false;
65 public $mConvRuleTitle = false;
68 public $mHeaderVariant;
69 public $mMaxDepth = 10;
70 public $mVarSeparatorPattern;
72 const CACHE_VERSION_KEY
= 'VERSION 7';
77 * @param Language $langobj
78 * @param string $maincode The main language code of this language
79 * @param array $variants The supported variants of this language
80 * @param array $variantfallbacks The fallback language of each variant
81 * @param array $flags Defining the custom strings that maps to the flags
82 * @param array $manualLevel Limit for supported variants
84 public function __construct( $langobj, $maincode, $variants = [],
85 $variantfallbacks = [], $flags = [],
87 global $wgDisabledVariants;
88 $this->mLangObj
= $langobj;
89 $this->mMainLanguageCode
= $maincode;
90 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
91 $this->mVariantFallbacks
= $variantfallbacks;
92 $this->mVariantNames
= Language
::fetchLanguageNames();
93 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
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 array 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 ) {
346 $toVariant = $this->getPreferredVariant();
352 if ( $this->guessVariant( $text, $toVariant ) ) {
356 /* we convert everything except:
357 1. HTML markups (anything between < and >)
359 3. placeholders created by the parser
361 $marker = '|' . Parser
::MARKER_PREFIX
. '[\-a-zA-Z0-9]+';
363 // this one is needed when the text is inside an HTML markup
364 $htmlfix = '|<[^>]+$|^[^<>]*>';
366 // disable convert to variants between <code> tags
367 $codefix = '<code>.+?<\/code>|';
368 // disable conversion of <script> tags
369 $scriptfix = '<script.*?>.*?<\/script>|';
370 // disable conversion of <pre> tags
371 $prefix = '<pre.*?>.*?<\/pre>|';
373 $reg = '/' . $codefix . $scriptfix . $prefix .
374 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
379 // Guard against delimiter nulls in the input
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 // Remove HTML tags to avoid disrupting the layout
416 $attr = preg_replace( '/<[^>]+>/', '', $attr );
417 if ( $attr !== $attrs[$attrName] ) {
418 $attrs[$attrName] = $attr;
423 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
427 $literalBlob .= $element . "\000";
430 // Do the main translation batch
431 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
433 // Put the output back together
434 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
435 $literalIter = StringUtils
::explode( "\000", $literalBlob );
437 while ( $translatedIter->valid() && $literalIter->valid() ) {
438 $output .= $translatedIter->current();
439 $output .= $literalIter->current();
440 $translatedIter->next();
441 $literalIter->next();
448 * Translate a string to a variant.
449 * Doesn't parse rules or do any of that other stuff, for that use
450 * convert() or convertTo().
452 * @param string $text Text to convert
453 * @param string $variant Variant language code
454 * @return string Translated text
456 public function translate( $text, $variant ) {
457 // If $text is empty or only includes spaces, do nothing
458 // Otherwise translate it
459 if ( trim( $text ) ) {
461 $text = $this->mTables
[$variant]->replace( $text );
467 * Call translate() to convert text to all valid variants.
469 * @param string $text The text to be converted
470 * @return array Variant => converted text
472 public function autoConvertToAllVariants( $text ) {
476 foreach ( $this->mVariants
as $variant ) {
477 $ret[$variant] = $this->translate( $text, $variant );
484 * Apply manual conversion rules.
486 * @param ConverterRule $convRule
488 protected function applyManualConv( $convRule ) {
489 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
491 // Bug 24072: $mConvRuleTitle was overwritten by other manual
492 // rule(s) not for title, this breaks the title conversion.
493 $newConvRuleTitle = $convRule->getTitle();
494 if ( $newConvRuleTitle ) {
495 // So I add an empty check for getTitle()
496 $this->mConvRuleTitle
= $newConvRuleTitle;
499 // merge/remove manual conversion rules to/from global table
500 $convTable = $convRule->getConvTable();
501 $action = $convRule->getRulesAction();
502 foreach ( $convTable as $variant => $pair ) {
503 if ( !$this->validateVariant( $variant ) ) {
507 if ( $action == 'add' ) {
508 // More efficient than array_merge(), about 2.5 times.
509 foreach ( $pair as $from => $to ) {
510 $this->mTables
[$variant]->setPair( $from, $to );
512 } elseif ( $action == 'remove' ) {
513 $this->mTables
[$variant]->removeArray( $pair );
519 * Auto convert a Title object to a readable string in the
522 * @param Title $title A object of Title
523 * @return string Converted title text
525 public function convertTitle( $title ) {
526 $variant = $this->getPreferredVariant();
527 $index = $title->getNamespace();
528 if ( $index !== NS_MAIN
) {
529 $text = $this->convertNamespace( $index, $variant ) . ':';
533 $text .= $this->translate( $title->getText(), $variant );
538 * Get the namespace display name in the preferred variant.
540 * @param int $index Namespace id
541 * @param string|null $variant Variant code or null for preferred variant
542 * @return string Namespace name for display
544 public function convertNamespace( $index, $variant = null ) {
545 if ( $index === NS_MAIN
) {
549 if ( $variant === null ) {
550 $variant = $this->getPreferredVariant();
553 $cache = ObjectCache
::newAccelerator( CACHE_NONE
);
554 $key = wfMemcKey( 'languageconverter', 'namespace-text', $index, $variant );
555 $nsVariantText = $cache->get( $key );
556 if ( $nsVariantText !== false ) {
557 return $nsVariantText;
560 // First check if a message gives a converted name in the target variant.
561 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
562 if ( $nsConvMsg->exists() ) {
563 $nsVariantText = $nsConvMsg->plain();
566 // Then check if a message gives a converted name in content language
567 // which needs extra translation to the target variant.
568 if ( $nsVariantText === false ) {
569 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
570 if ( $nsConvMsg->exists() ) {
571 $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
575 if ( $nsVariantText === false ) {
576 // No message exists, retrieve it from the target variant's namespace names.
577 $langObj = $this->mLangObj
->factory( $variant );
578 $nsVariantText = $langObj->getFormattedNsText( $index );
581 $cache->set( $key, $nsVariantText, 60 );
583 return $nsVariantText;
587 * Convert text to different variants of a language. The automatic
588 * conversion is done in autoConvert(). Here we parse the text
589 * marked with -{}-, which specifies special conversions of the
590 * text that can not be accomplished in autoConvert().
592 * Syntax of the markup:
593 * -{code1:text1;code2:text2;...}- or
594 * -{flags|code1:text1;code2:text2;...}- or
595 * -{text}- in which case no conversion should take place for text
597 * @param string $text Text to be converted
598 * @return string Converted text
600 public function convert( $text ) {
601 $variant = $this->getPreferredVariant();
602 return $this->convertTo( $text, $variant );
606 * Same as convert() except a extra parameter to custom variant.
608 * @param string $text Text to be converted
609 * @param string $variant The target variant code
610 * @return string Converted text
612 public function convertTo( $text, $variant ) {
613 global $wgDisableLangConversion;
614 if ( $wgDisableLangConversion ) {
617 // Reset converter state for a new converter run.
618 $this->mConvRuleTitle
= false;
619 return $this->recursiveConvertTopLevel( $text, $variant );
623 * Recursively convert text on the outside. Allow to use nested
624 * markups to custom rules.
626 * @param string $text Text to be converted
627 * @param string $variant The target variant code
628 * @param int $depth Depth of recursion
629 * @return string Converted text
631 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
634 $length = strlen( $text );
635 $shouldConvert = !$this->guessVariant( $text, $variant );
637 while ( $startPos < $length ) {
638 $pos = strpos( $text, '-{', $startPos );
640 if ( $pos === false ) {
641 // No more markup, append final segment
642 $fragment = substr( $text, $startPos );
643 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
648 // Append initial segment
649 $fragment = substr( $text, $startPos, $pos - $startPos );
650 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
655 // Do recursive conversion
656 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
663 * Recursively convert text on the inside.
665 * @param string $text Text to be converted
666 * @param string $variant The target variant code
667 * @param int $startPos
668 * @param int $depth Depth of recursion
670 * @throws MWException
671 * @return string Converted text
673 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
674 // Quick sanity check (no function calls)
675 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
676 throw new MWException( __METHOD__
. ': invalid input string' );
681 $warningDone = false;
682 $length = strlen( $text );
684 while ( $startPos < $length ) {
686 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
696 // Append initial segment
697 $inner .= substr( $text, $startPos, $pos - $startPos );
705 if ( $depth >= $this->mMaxDepth
) {
707 if ( !$warningDone ) {
708 $inner .= '<span class="error">' .
709 wfMessage( 'language-converter-depth-warning' )
710 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
717 // Recursively parse another rule
718 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
723 $rule = new ConverterRule( $inner, $this );
724 $rule->parse( $variant );
725 $this->applyManualConv( $rule );
726 return $rule->getDisplay();
728 throw new MWException( __METHOD__
. ': invalid regex match' );
733 if ( $startPos < $length ) {
734 $inner .= substr( $text, $startPos );
737 return '-{' . $this->autoConvert( $inner, $variant );
741 * If a language supports multiple variants, it is possible that
742 * non-existing link in one variant actually exists in another variant.
743 * This function tries to find it. See e.g. LanguageZh.php
744 * The input parameters may be modified upon return
746 * @param string &$link The name of the link
747 * @param Title &$nt The title object of the link
748 * @param bool $ignoreOtherCond To disable other conditions when
749 * we need to transclude a template or update a category's link
751 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
752 # If the article has already existed, there is no need to
753 # check it again, otherwise it may cause a fault.
754 if ( is_object( $nt ) && $nt->exists() ) {
758 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
759 $isredir = $wgRequest->getText( 'redirect', 'yes' );
760 $action = $wgRequest->getText( 'action' );
761 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
764 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
765 $disableLinkConversion = $wgDisableLangConversion
766 ||
$wgDisableTitleConversion;
767 $linkBatch = new LinkBatch();
771 if ( $disableLinkConversion ||
772 ( !$ignoreOtherCond &&
775 ||
$action == 'submit'
776 ||
$linkconvert == 'no' ) ) ) {
780 if ( is_object( $nt ) ) {
781 $ns = $nt->getNamespace();
784 $variants = $this->autoConvertToAllVariants( $link );
785 if ( !$variants ) { // give up
791 foreach ( $variants as $v ) {
793 $varnt = Title
::newFromText( $v, $ns );
794 if ( !is_null( $varnt ) ) {
795 $linkBatch->addObj( $varnt );
801 // fetch all variants in single query
802 $linkBatch->execute();
804 foreach ( $titles as $varnt ) {
805 if ( $varnt->getArticleID() > 0 ) {
807 $link = $varnt->getText();
814 * Returns language specific hash options.
818 public function getExtraHashOptions() {
819 $variant = $this->getPreferredVariant();
821 return '!' . $variant;
825 * Guess if a text is written in a variant. This should be implemented in subclasses.
827 * @param string $text The text to be checked
828 * @param string $variant Language code of the variant to be checked for
829 * @return bool True if $text appears to be written in $variant, false if not
831 * @author Nikola Smolenski <smolensk@eunet.rs>
834 public function guessVariant( $text, $variant ) {
839 * Load default conversion tables.
840 * This method must be implemented in derived class.
843 * @throws MWException
845 function loadDefaultTables() {
846 $name = get_class( $this );
848 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
852 * Load conversion tables either from the cache or the disk.
854 * @param bool $fromCache Load from memcached? Defaults to true.
856 function loadTables( $fromCache = true ) {
857 global $wgLanguageConverterCacheType;
859 if ( $this->mTablesLoaded
) {
863 $this->mTablesLoaded
= true;
864 $this->mTables
= false;
865 $cache = ObjectCache
::getInstance( $wgLanguageConverterCacheType );
867 wfProfileIn( __METHOD__
. '-cache' );
868 $this->mTables
= $cache->get( $this->mCacheKey
);
869 wfProfileOut( __METHOD__
. '-cache' );
871 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
872 wfProfileIn( __METHOD__
. '-recache' );
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 );
886 wfProfileOut( __METHOD__
. '-recache' );
891 * Hook for post processing after conversion tables are loaded.
893 function postLoadTables() {
897 * Reload the conversion tables.
901 function reloadTables() {
902 if ( $this->mTables
) {
903 unset( $this->mTables
);
906 $this->mTablesLoaded
= false;
907 $this->loadTables( false );
911 * Parse the conversion table stored in the cache.
913 * The tables should be in blocks of the following form:
920 * To make the tables more manageable, subpages are allowed
921 * and will be parsed recursively if $recursive == true.
923 * @param string $code Language code
924 * @param string $subpage Subpage name
925 * @param bool $recursive Parse subpages recursively? Defaults to true.
929 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
932 $key = 'Conversiontable/' . $code;
934 $key .= '/' . $subpage;
936 if ( array_key_exists( $key, $parsed ) ) {
940 $parsed[$key] = true;
942 if ( $subpage === '' ) {
943 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
946 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
947 if ( $title && $title->exists() ) {
948 $revision = Revision
::newFromTitle( $title );
950 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
951 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
954 // @todo in the future, use a specialized content model, perhaps based on json!
959 # Nothing to parse if there's no text
960 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
964 // get all subpage links of the form
965 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
966 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
968 $subs = StringUtils
::explode( '[[', $txt );
970 foreach ( $subs as $sub ) {
971 $link = explode( ']]', $sub, 2 );
972 if ( count( $link ) != 2 ) {
975 $b = explode( '|', $link[0], 2 );
976 $b = explode( '/', trim( $b[0] ), 3 );
977 if ( count( $b ) == 3 ) {
983 if ( $b[0] == $linkhead && $b[1] == $code ) {
984 $sublinks[] = $sublink;
988 // parse the mappings in this page
989 $blocks = StringUtils
::explode( '-{', $txt );
992 foreach ( $blocks as $block ) {
994 // Skip the part before the first -{
998 $mappings = explode( '}-', $block, 2 )[0];
999 $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
1000 $table = StringUtils
::explode( ';', $stripped );
1001 foreach ( $table as $t ) {
1002 $m = explode( '=>', $t, 3 );
1003 if ( count( $m ) != 2 ) {
1006 // trim any trailling comments starting with '//'
1007 $tt = explode( '//', $m[1], 2 );
1008 $ret[trim( $m[0] )] = trim( $tt[0] );
1012 // recursively parse the subpages
1014 foreach ( $sublinks as $link ) {
1015 $s = $this->parseCachedTable( $code, $link, $recursive );
1020 if ( $this->mUcfirst
) {
1021 foreach ( $ret as $k => $v ) {
1022 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1029 * Enclose a string with the "no conversion" tag. This is used by
1030 * various functions in the Parser.
1032 * @param string $text Text to be tagged for no conversion
1033 * @param bool $noParse Unused
1034 * @return string The tagged text
1036 public function markNoConversion( $text, $noParse = false ) {
1037 # don't mark if already marked
1038 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1042 $ret = "-{R|$text}-";
1047 * Convert the sorting key for category links. This should make different
1048 * keys that are variants of each other map to the same key.
1050 * @param string $key
1054 function convertCategoryKey( $key ) {
1059 * Refresh the cache of conversion tables when
1060 * MediaWiki:Conversiontable* is updated.
1062 * @param Title $titleobj The Title of the page being updated
1064 public function updateConversionTable( Title
$titleobj ) {
1065 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1066 $title = $titleobj->getDBkey();
1067 $t = explode( '/', $title, 3 );
1069 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1070 if ( $this->validateVariant( $t[1] ) ) {
1071 $this->reloadTables();
1078 * Get the cached separator pattern for ConverterRule::parseRules()
1081 function getVarSeparatorPattern() {
1082 if ( is_null( $this->mVarSeparatorPattern
) ) {
1083 // varsep_pattern for preg_split:
1084 // text should be splited by ";" only if a valid variant
1085 // name exist after the markup, for example:
1086 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1087 // <span style="font-size:120%;">yyy</span>;}-
1088 // we should split it as:
1090 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1091 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1095 foreach ( $this->mVariants
as $variant ) {
1096 // zh-hans:xxx;zh-hant:yyy
1097 $pat .= $variant . '\s*:|';
1098 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1099 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1102 $this->mVarSeparatorPattern
= $pat;
1104 return $this->mVarSeparatorPattern
;