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 = array(
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 = array(),
85 $variantfallbacks = array(), $flags = array(),
86 $manualLevel = array() ) {
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 );
94 $defaultflags = array(
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->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->isLoggedIn() ) {
261 if ( $this->mMainLanguageCode
== $wgContLang->getCode() ) {
262 $ret = $wgUser->getOption( 'variant' );
264 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode
);
267 // figure out user lang without constructing wgLang to avoid
268 // infinite recursion
269 $ret = $wgUser->getOption( 'language' );
272 $this->mUserVariant
= $this->validateVariant( $ret );
273 return $this->mUserVariant
;
277 * Determine the language variant from the Accept-Language header.
279 * @return mixed Variant if one found, false otherwise.
281 protected function getHeaderVariant() {
284 if ( $this->mHeaderVariant
) {
285 return $this->mHeaderVariant
;
288 // see if some supported language variant is set in the
290 $languages = array_keys( $wgRequest->getAcceptLang() );
291 if ( empty( $languages ) ) {
295 $fallbackLanguages = array();
296 foreach ( $languages as $language ) {
297 $this->mHeaderVariant
= $this->validateVariant( $language );
298 if ( $this->mHeaderVariant
) {
302 // To see if there are fallbacks of current language.
303 // We record these fallback variants, and process
305 $fallbacks = $this->getVariantFallbacks( $language );
306 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
307 $fallbackLanguages[] = $fallbacks;
308 } elseif ( is_array( $fallbacks ) ) {
310 array_merge( $fallbackLanguages, $fallbacks );
314 if ( !$this->mHeaderVariant
) {
315 // process fallback languages now
316 $fallback_languages = array_unique( $fallbackLanguages );
317 foreach ( $fallback_languages as $language ) {
318 $this->mHeaderVariant
= $this->validateVariant( $language );
319 if ( $this->mHeaderVariant
) {
325 return $this->mHeaderVariant
;
329 * Dictionary-based conversion.
330 * This function would not parse the conversion rules.
331 * If you want to parse rules, try to use convert() or
334 * @param string $text The text to be converted
335 * @param bool|string $toVariant The target language code
336 * @return string The converted text
338 public function autoConvert( $text, $toVariant = false ) {
343 $toVariant = $this->getPreferredVariant();
349 if ( $this->guessVariant( $text, $toVariant ) ) {
353 /* we convert everything except:
354 1. HTML markups (anything between < and >)
356 3. placeholders created by the parser
358 $marker = '|' . Parser
::MARKER_PREFIX
. '[\-a-zA-Z0-9]+';
360 // this one is needed when the text is inside an HTML markup
361 $htmlfix = '|<[^>]+$|^[^<>]*>';
363 // disable convert to variants between <code> tags
364 $codefix = '<code>.+?<\/code>|';
365 // disable conversion of <script> tags
366 $scriptfix = '<script.*?>.*?<\/script>|';
367 // disable conversion of <pre> tags
368 $prefix = '<pre.*?>.*?<\/pre>|';
370 $reg = '/' . $codefix . $scriptfix . $prefix .
371 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
376 // Guard against delimiter nulls in the input
377 $text = str_replace( "\000", '', $text );
379 $markupMatches = null;
380 $elementMatches = null;
381 while ( $startPos < strlen( $text ) ) {
382 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
383 $elementPos = $markupMatches[0][1];
384 $element = $markupMatches[0][0];
386 $elementPos = strlen( $text );
390 // Queue the part before the markup for translation in a batch
391 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
393 // Advance to the next position
394 $startPos = $elementPos +
strlen( $element );
396 // Translate any alt or title attributes inside the matched element
398 && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element, $elementMatches )
400 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
402 foreach ( array( 'title', 'alt' ) as $attrName ) {
403 if ( !isset( $attrs[$attrName] ) ) {
406 $attr = $attrs[$attrName];
407 // Don't convert URLs
408 if ( !strpos( $attr, '://' ) ) {
409 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
412 // Remove HTML tags to avoid disrupting the layout
413 $attr = preg_replace( '/<[^>]+>/', '', $attr );
414 if ( $attr !== $attrs[$attrName] ) {
415 $attrs[$attrName] = $attr;
420 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
424 $literalBlob .= $element . "\000";
427 // Do the main translation batch
428 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
430 // Put the output back together
431 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
432 $literalIter = StringUtils
::explode( "\000", $literalBlob );
434 while ( $translatedIter->valid() && $literalIter->valid() ) {
435 $output .= $translatedIter->current();
436 $output .= $literalIter->current();
437 $translatedIter->next();
438 $literalIter->next();
445 * Translate a string to a variant.
446 * Doesn't parse rules or do any of that other stuff, for that use
447 * convert() or convertTo().
449 * @param string $text Text to convert
450 * @param string $variant Variant language code
451 * @return string Translated text
453 public function translate( $text, $variant ) {
454 // If $text is empty or only includes spaces, do nothing
455 // Otherwise translate it
456 if ( trim( $text ) ) {
458 $text = $this->mTables
[$variant]->replace( $text );
464 * Call translate() to convert text to all valid variants.
466 * @param string $text The text to be converted
467 * @return array Variant => converted text
469 public function autoConvertToAllVariants( $text ) {
473 foreach ( $this->mVariants
as $variant ) {
474 $ret[$variant] = $this->translate( $text, $variant );
481 * Apply manual conversion rules.
483 * @param ConverterRule $convRule
485 protected function applyManualConv( $convRule ) {
486 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
488 // Bug 24072: $mConvRuleTitle was overwritten by other manual
489 // rule(s) not for title, this breaks the title conversion.
490 $newConvRuleTitle = $convRule->getTitle();
491 if ( $newConvRuleTitle ) {
492 // So I add an empty check for getTitle()
493 $this->mConvRuleTitle
= $newConvRuleTitle;
496 // merge/remove manual conversion rules to/from global table
497 $convTable = $convRule->getConvTable();
498 $action = $convRule->getRulesAction();
499 foreach ( $convTable as $variant => $pair ) {
500 if ( !$this->validateVariant( $variant ) ) {
504 if ( $action == 'add' ) {
505 // More efficient than array_merge(), about 2.5 times.
506 foreach ( $pair as $from => $to ) {
507 $this->mTables
[$variant]->setPair( $from, $to );
509 } elseif ( $action == 'remove' ) {
510 $this->mTables
[$variant]->removeArray( $pair );
516 * Auto convert a Title object to a readable string in the
519 * @param Title $title A object of Title
520 * @return string Converted title text
522 public function convertTitle( $title ) {
523 $variant = $this->getPreferredVariant();
524 $index = $title->getNamespace();
525 if ( $index !== NS_MAIN
) {
526 $text = $this->convertNamespace( $index, $variant ) . ':';
530 $text .= $this->translate( $title->getText(), $variant );
535 * Get the namespace display name in the preferred variant.
537 * @param int $index Namespace id
538 * @param string|null $variant Variant code or null for preferred variant
539 * @return string Namespace name for display
541 public function convertNamespace( $index, $variant = null ) {
542 if ( $index === NS_MAIN
) {
546 if ( $variant === null ) {
547 $variant = $this->getPreferredVariant();
550 $cache = ObjectCache
::newAccelerator( CACHE_NONE
);
551 $key = wfMemcKey( 'languageconverter', 'namespace-text', $index, $variant );
552 $nsVariantText = $cache->get( $key );
553 if ( $nsVariantText !== false ) {
554 return $nsVariantText;
557 // First check if a message gives a converted name in the target variant.
558 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
559 if ( $nsConvMsg->exists() ) {
560 $nsVariantText = $nsConvMsg->plain();
563 // Then check if a message gives a converted name in content language
564 // which needs extra translation to the target variant.
565 if ( $nsVariantText === false ) {
566 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
567 if ( $nsConvMsg->exists() ) {
568 $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
572 if ( $nsVariantText === false ) {
573 // No message exists, retrieve it from the target variant's namespace names.
574 $langObj = $this->mLangObj
->factory( $variant );
575 $nsVariantText = $langObj->getFormattedNsText( $index );
578 $cache->set( $key, $nsVariantText, 60 );
580 return $nsVariantText;
584 * Convert text to different variants of a language. The automatic
585 * conversion is done in autoConvert(). Here we parse the text
586 * marked with -{}-, which specifies special conversions of the
587 * text that can not be accomplished in autoConvert().
589 * Syntax of the markup:
590 * -{code1:text1;code2:text2;...}- or
591 * -{flags|code1:text1;code2:text2;...}- or
592 * -{text}- in which case no conversion should take place for text
594 * @param string $text Text to be converted
595 * @return string Converted text
597 public function convert( $text ) {
598 $variant = $this->getPreferredVariant();
599 return $this->convertTo( $text, $variant );
603 * Same as convert() except a extra parameter to custom variant.
605 * @param string $text Text to be converted
606 * @param string $variant The target variant code
607 * @return string Converted text
609 public function convertTo( $text, $variant ) {
610 global $wgDisableLangConversion;
611 if ( $wgDisableLangConversion ) {
614 // Reset converter state for a new converter run.
615 $this->mConvRuleTitle
= false;
616 return $this->recursiveConvertTopLevel( $text, $variant );
620 * Recursively convert text on the outside. Allow to use nested
621 * markups to custom rules.
623 * @param string $text Text to be converted
624 * @param string $variant The target variant code
625 * @param int $depth Depth of recursion
626 * @return string Converted text
628 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
631 $length = strlen( $text );
632 $shouldConvert = !$this->guessVariant( $text, $variant );
634 while ( $startPos < $length ) {
635 $pos = strpos( $text, '-{', $startPos );
637 if ( $pos === false ) {
638 // No more markup, append final segment
639 $fragment = substr( $text, $startPos );
640 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
645 // Append initial segment
646 $fragment = substr( $text, $startPos, $pos - $startPos );
647 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
652 // Do recursive conversion
653 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
660 * Recursively convert text on the inside.
662 * @param string $text Text to be converted
663 * @param string $variant The target variant code
664 * @param int $startPos
665 * @param int $depth Depth of recursion
667 * @throws MWException
668 * @return string Converted text
670 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
671 // Quick sanity check (no function calls)
672 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
673 throw new MWException( __METHOD__
. ': invalid input string' );
678 $warningDone = false;
679 $length = strlen( $text );
681 while ( $startPos < $length ) {
683 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
693 // Append initial segment
694 $inner .= substr( $text, $startPos, $pos - $startPos );
702 if ( $depth >= $this->mMaxDepth
) {
704 if ( !$warningDone ) {
705 $inner .= '<span class="error">' .
706 wfMessage( 'language-converter-depth-warning' )
707 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
714 // Recursively parse another rule
715 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
720 $rule = new ConverterRule( $inner, $this );
721 $rule->parse( $variant );
722 $this->applyManualConv( $rule );
723 return $rule->getDisplay();
725 throw new MWException( __METHOD__
. ': invalid regex match' );
730 if ( $startPos < $length ) {
731 $inner .= substr( $text, $startPos );
734 return '-{' . $this->autoConvert( $inner, $variant );
738 * If a language supports multiple variants, it is possible that
739 * non-existing link in one variant actually exists in another variant.
740 * This function tries to find it. See e.g. LanguageZh.php
741 * The input parameters may be modified upon return
743 * @param string &$link The name of the link
744 * @param Title &$nt The title object of the link
745 * @param bool $ignoreOtherCond To disable other conditions when
746 * we need to transclude a template or update a category's link
748 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
749 # If the article has already existed, there is no need to
750 # check it again, otherwise it may cause a fault.
751 if ( is_object( $nt ) && $nt->exists() ) {
755 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
756 $isredir = $wgRequest->getText( 'redirect', 'yes' );
757 $action = $wgRequest->getText( 'action' );
758 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
761 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
762 $disableLinkConversion = $wgDisableLangConversion
763 ||
$wgDisableTitleConversion;
764 $linkBatch = new LinkBatch();
768 if ( $disableLinkConversion ||
769 ( !$ignoreOtherCond &&
772 ||
$action == 'submit'
773 ||
$linkconvert == 'no' ) ) ) {
777 if ( is_object( $nt ) ) {
778 $ns = $nt->getNamespace();
781 $variants = $this->autoConvertToAllVariants( $link );
782 if ( !$variants ) { // give up
788 foreach ( $variants as $v ) {
790 $varnt = Title
::newFromText( $v, $ns );
791 if ( !is_null( $varnt ) ) {
792 $linkBatch->addObj( $varnt );
798 // fetch all variants in single query
799 $linkBatch->execute();
801 foreach ( $titles as $varnt ) {
802 if ( $varnt->getArticleID() > 0 ) {
804 $link = $varnt->getText();
811 * Returns language specific hash options.
815 public function getExtraHashOptions() {
816 $variant = $this->getPreferredVariant();
818 return '!' . $variant;
822 * Guess if a text is written in a variant. This should be implemented in subclasses.
824 * @param string $text The text to be checked
825 * @param string $variant Language code of the variant to be checked for
826 * @return bool True if $text appears to be written in $variant, false if not
828 * @author Nikola Smolenski <smolensk@eunet.rs>
831 public function guessVariant( $text, $variant ) {
836 * Load default conversion tables.
837 * This method must be implemented in derived class.
840 * @throws MWException
842 function loadDefaultTables() {
843 $name = get_class( $this );
845 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
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 );
864 wfProfileIn( __METHOD__
. '-cache' );
865 $this->mTables
= $cache->get( $this->mCacheKey
);
866 wfProfileOut( __METHOD__
. '-cache' );
868 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
869 wfProfileIn( __METHOD__
. '-recache' );
870 // not in cache, or we need a fresh reload.
871 // We will first load the default tables
872 // then update them using things in MediaWiki:Conversiontable/*
873 $this->loadDefaultTables();
874 foreach ( $this->mVariants
as $var ) {
875 $cached = $this->parseCachedTable( $var );
876 $this->mTables
[$var]->mergeArray( $cached );
879 $this->postLoadTables();
880 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
882 $cache->set( $this->mCacheKey
, $this->mTables
, 43200 );
883 wfProfileOut( __METHOD__
. '-recache' );
888 * Hook for post processing after conversion tables are loaded.
890 function postLoadTables() {
894 * Reload the conversion tables.
898 function reloadTables() {
899 if ( $this->mTables
) {
900 unset( $this->mTables
);
903 $this->mTablesLoaded
= false;
904 $this->loadTables( false );
908 * Parse the conversion table stored in the cache.
910 * The tables should be in blocks of the following form:
917 * To make the tables more manageable, subpages are allowed
918 * and will be parsed recursively if $recursive == true.
920 * @param string $code Language code
921 * @param string $subpage Subpage name
922 * @param bool $recursive Parse subpages recursively? Defaults to true.
926 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
927 static $parsed = array();
929 $key = 'Conversiontable/' . $code;
931 $key .= '/' . $subpage;
933 if ( array_key_exists( $key, $parsed ) ) {
937 $parsed[$key] = true;
939 if ( $subpage === '' ) {
940 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
943 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
944 if ( $title && $title->exists() ) {
945 $revision = Revision
::newFromTitle( $title );
947 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
948 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
951 // @todo in the future, use a specialized content model, perhaps based on json!
956 # Nothing to parse if there's no text
957 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
961 // get all subpage links of the form
962 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
963 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
965 $subs = StringUtils
::explode( '[[', $txt );
967 foreach ( $subs as $sub ) {
968 $link = explode( ']]', $sub, 2 );
969 if ( count( $link ) != 2 ) {
972 $b = explode( '|', $link[0], 2 );
973 $b = explode( '/', trim( $b[0] ), 3 );
974 if ( count( $b ) == 3 ) {
980 if ( $b[0] == $linkhead && $b[1] == $code ) {
981 $sublinks[] = $sublink;
985 // parse the mappings in this page
986 $blocks = StringUtils
::explode( '-{', $txt );
989 foreach ( $blocks as $block ) {
991 // Skip the part before the first -{
995 $mappings = explode( '}-', $block, 2 );
996 $stripped = str_replace( array( "'", '"', '*', '#' ), '', $mappings[0] );
997 $table = StringUtils
::explode( ';', $stripped );
998 foreach ( $table as $t ) {
999 $m = explode( '=>', $t, 3 );
1000 if ( count( $m ) != 2 ) {
1003 // trim any trailling comments starting with '//'
1004 $tt = explode( '//', $m[1], 2 );
1005 $ret[trim( $m[0] )] = trim( $tt[0] );
1009 // recursively parse the subpages
1011 foreach ( $sublinks as $link ) {
1012 $s = $this->parseCachedTable( $code, $link, $recursive );
1017 if ( $this->mUcfirst
) {
1018 foreach ( $ret as $k => $v ) {
1019 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1026 * Enclose a string with the "no conversion" tag. This is used by
1027 * various functions in the Parser.
1029 * @param string $text Text to be tagged for no conversion
1030 * @param bool $noParse Unused
1031 * @return string The tagged text
1033 public function markNoConversion( $text, $noParse = false ) {
1034 # don't mark if already marked
1035 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1039 $ret = "-{R|$text}-";
1044 * Convert the sorting key for category links. This should make different
1045 * keys that are variants of each other map to the same key.
1047 * @param string $key
1051 function convertCategoryKey( $key ) {
1056 * Hook to refresh the cache of conversion tables when
1057 * MediaWiki:Conversiontable* is updated.
1060 * @param WikiPage $page
1061 * @param User $user User object for the current user
1062 * @param Content $content New page content
1063 * @param string $summary Edit summary of the edit
1064 * @param bool $isMinor Was the edit marked as minor?
1065 * @param null $isWatch Unused.
1066 * @param null $section Unused.
1067 * @param int $flags Bitfield
1068 * @param Revision|null $revision New Revision object or null
1071 function OnPageContentSaveComplete( $page, $user, $content, $summary, $isMinor,
1072 $isWatch, $section, $flags, $revision ) {
1073 $titleobj = $page->getTitle();
1074 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1075 $title = $titleobj->getDBkey();
1076 $t = explode( '/', $title, 3 );
1078 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1079 if ( $this->validateVariant( $t[1] ) ) {
1080 $this->reloadTables();
1088 * Get the cached separator pattern for ConverterRule::parseRules()
1091 function getVarSeparatorPattern() {
1092 if ( is_null( $this->mVarSeparatorPattern
) ) {
1093 // varsep_pattern for preg_split:
1094 // text should be splited by ";" only if a valid variant
1095 // name exist after the markup, for example:
1096 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1097 // <span style="font-size:120%;">yyy</span>;}-
1098 // we should split it as:
1100 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1101 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1105 foreach ( $this->mVariants
as $variant ) {
1106 // zh-hans:xxx;zh-hant:yyy
1107 $pat .= $variant . '\s*:|';
1108 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1109 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1112 $this->mVarSeparatorPattern
= $pat;
1114 return $this->mVarSeparatorPattern
;