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 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>, PhiLiP <philip.npc@gmail.com>
29 class LanguageConverter
{
32 * languages supporting variants
36 static public $languagesWithVariants = array(
48 public $mMainLanguageCode;
49 public $mVariants, $mVariantFallbacks, $mVariantNames;
50 public $mTablesLoaded = false;
52 // 'bidirectional' 'unidirectional' 'disable' for each variant
56 * @var string memcached key name
62 public $mDescCodeSep = ':', $mDescVarSep = ';';
63 public $mUcfirst = false;
64 public $mConvRuleTitle = false;
67 public $mHeaderVariant;
68 public $mMaxDepth = 10;
69 public $mVarSeparatorPattern;
71 const CACHE_VERSION_KEY
= 'VERSION 7';
76 * @param Language $langobj
77 * @param string $maincode The main language code of this language
78 * @param array $variants The supported variants of this language
79 * @param array $variantfallbacks The fallback language of each variant
80 * @param array $flags Defining the custom strings that maps to the flags
81 * @param array $manualLevel Limit for supported variants
83 public function __construct( $langobj, $maincode, $variants = array(),
84 $variantfallbacks = array(), $flags = array(),
85 $manualLevel = array() ) {
86 global $wgDisabledVariants;
87 $this->mLangObj
= $langobj;
88 $this->mMainLanguageCode
= $maincode;
89 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
90 $this->mVariantFallbacks
= $variantfallbacks;
91 $this->mVariantNames
= Language
::fetchLanguageNames();
92 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
93 $defaultflags = array(
94 // 'S' show converted text
95 // '+' add rules for alltext
96 // 'E' the gave flags is error
97 // these flags above are reserved for program
98 'A' => 'A', // add rule for convert code (all text convert)
99 'T' => 'T', // title convert
100 'R' => 'R', // raw content
101 'D' => 'D', // convert description (subclass implement)
102 '-' => '-', // remove convert (not implement)
103 'H' => 'H', // add rule for convert code (but no display in placed code)
104 'N' => 'N' // current variant name
106 $this->mFlags
= array_merge( $defaultflags, $flags );
107 foreach ( $this->mVariants
as $v ) {
108 if ( array_key_exists( $v, $manualLevel ) ) {
109 $this->mManualLevel
[$v] = $manualLevel[$v];
111 $this->mManualLevel
[$v] = 'bidirectional';
113 $this->mFlags
[$v] = $v;
118 * Get all valid variants.
119 * Call this instead of using $this->mVariants directly.
121 * @return array Contains all valid variants
123 public function getVariants() {
124 return $this->mVariants
;
128 * In case some variant is not defined in the markup, we need
129 * to have some fallback. For example, in zh, normally people
130 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
131 * when zh-sg is preferred but not defined, we will pick zh-hans
132 * in this case. Right now this is only used by zh.
134 * @param string $variant The language code of the variant
135 * @return string|array The code of the fallback language or the
136 * main code if there is no fallback
138 public function getVariantFallbacks( $variant ) {
139 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
140 return $this->mVariantFallbacks
[$variant];
142 return $this->mMainLanguageCode
;
146 * Get the title produced by the conversion rule.
147 * @return string The converted title text
149 public function getConvRuleTitle() {
150 return $this->mConvRuleTitle
;
154 * Get preferred language variant.
155 * @return string The preferred language code
157 public function getPreferredVariant() {
158 global $wgDefaultLanguageVariant, $wgUser;
160 $req = $this->getURLVariant();
162 if ( $wgUser->isLoggedIn() && !$req ) {
163 $req = $this->getUserVariant();
165 $req = $this->getHeaderVariant();
168 if ( $wgDefaultLanguageVariant && !$req ) {
169 $req = $this->validateVariant( $wgDefaultLanguageVariant );
172 // This function, unlike the other get*Variant functions, is
173 // not memoized (i.e. there return value is not cached) since
174 // new information might appear during processing after this
176 if ( $this->validateVariant( $req ) ) {
179 return $this->mMainLanguageCode
;
183 * Get default variant.
184 * This function would not be affected by user's settings
185 * @return string The default variant code
187 public function getDefaultVariant() {
188 global $wgDefaultLanguageVariant;
190 $req = $this->getURLVariant();
193 $req = $this->getHeaderVariant();
196 if ( $wgDefaultLanguageVariant && !$req ) {
197 $req = $this->validateVariant( $wgDefaultLanguageVariant );
203 return $this->mMainLanguageCode
;
207 * Validate the variant
208 * @param string $variant The variant to validate
209 * @return mixed Returns the variant if it is valid, null otherwise
211 public function validateVariant( $variant = null ) {
212 if ( $variant !== null && in_array( $variant, $this->mVariants
) ) {
219 * Get the variant specified in the URL
221 * @return mixed Variant if one found, false otherwise.
223 public function getURLVariant() {
226 if ( $this->mURLVariant
) {
227 return $this->mURLVariant
;
230 // see if the preference is set in the request
231 $ret = $wgRequest->getText( 'variant' );
234 $ret = $wgRequest->getVal( 'uselang' );
237 $this->mURLVariant
= $this->validateVariant( $ret );
238 return $this->mURLVariant
;
242 * Determine if the user has a variant set.
244 * @return mixed Variant if one found, false otherwise.
246 protected function getUserVariant() {
247 global $wgUser, $wgContLang;
249 // memoizing this function wreaks havoc on parserTest.php
251 if ( $this->mUserVariant ) {
252 return $this->mUserVariant;
256 // Get language variant preference from logged in users
257 // Don't call this on stub objects because that causes infinite
258 // recursion during initialisation
259 if ( $wgUser->isLoggedIn() ) {
260 if ( $this->mMainLanguageCode
== $wgContLang->getCode() ) {
261 $ret = $wgUser->getOption( 'variant' );
263 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode
);
266 // figure out user lang without constructing wgLang to avoid
267 // infinite recursion
268 $ret = $wgUser->getOption( 'language' );
271 $this->mUserVariant
= $this->validateVariant( $ret );
272 return $this->mUserVariant
;
276 * Determine the language variant from the Accept-Language header.
278 * @return mixed Variant if one found, false otherwise.
280 protected function getHeaderVariant() {
283 if ( $this->mHeaderVariant
) {
284 return $this->mHeaderVariant
;
287 // see if some supported language variant is set in the
289 $languages = array_keys( $wgRequest->getAcceptLang() );
290 if ( empty( $languages ) ) {
294 $fallbackLanguages = array();
295 foreach ( $languages as $language ) {
296 $this->mHeaderVariant
= $this->validateVariant( $language );
297 if ( $this->mHeaderVariant
) {
301 // To see if there are fallbacks of current language.
302 // We record these fallback variants, and process
304 $fallbacks = $this->getVariantFallbacks( $language );
305 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
306 $fallbackLanguages[] = $fallbacks;
307 } elseif ( is_array( $fallbacks ) ) {
309 array_merge( $fallbackLanguages, $fallbacks );
313 if ( !$this->mHeaderVariant
) {
314 // process fallback languages now
315 $fallback_languages = array_unique( $fallbackLanguages );
316 foreach ( $fallback_languages as $language ) {
317 $this->mHeaderVariant
= $this->validateVariant( $language );
318 if ( $this->mHeaderVariant
) {
324 return $this->mHeaderVariant
;
328 * Dictionary-based conversion.
329 * This function would not parse the conversion rules.
330 * If you want to parse rules, try to use convert() or
333 * @param $text String the text to be converted
334 * @param $toVariant bool|string the target language code
335 * @return String the converted text
337 public function autoConvert( $text, $toVariant = false ) {
338 wfProfileIn( __METHOD__
);
343 $toVariant = $this->getPreferredVariant();
345 wfProfileOut( __METHOD__
);
350 if ( $this->guessVariant( $text, $toVariant ) ) {
351 wfProfileOut( __METHOD__
);
355 /* we convert everything except:
356 1. HTML markups (anything between < and >)
358 3. placeholders created by the parser
361 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
362 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
367 // this one is needed when the text is inside an HTML markup
368 $htmlfix = '|<[^>]+$|^[^<>]*>';
370 // disable convert to variants between <code> tags
371 $codefix = '<code>.+?<\/code>|';
372 // disable conversion of <script> tags
373 $scriptfix = '<script.*?>.*?<\/script>|';
374 // disable conversion of <pre> tags
375 $prefix = '<pre.*?>.*?<\/pre>|';
377 $reg = '/' . $codefix . $scriptfix . $prefix .
378 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
383 // Guard against delimiter nulls in the input
384 $text = str_replace( "\000", '', $text );
386 $markupMatches = null;
387 $elementMatches = null;
388 while ( $startPos < strlen( $text ) ) {
389 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
390 $elementPos = $markupMatches[0][1];
391 $element = $markupMatches[0][0];
393 $elementPos = strlen( $text );
397 // Queue the part before the markup for translation in a batch
398 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
400 // Advance to the next position
401 $startPos = $elementPos +
strlen( $element );
403 // Translate any alt or title attributes inside the matched element
405 && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element, $elementMatches )
407 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
409 foreach ( array( 'title', 'alt' ) as $attrName ) {
410 if ( !isset( $attrs[$attrName] ) ) {
413 $attr = $attrs[$attrName];
414 // Don't convert URLs
415 if ( !strpos( $attr, '://' ) ) {
416 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
419 // Remove HTML tags to avoid disrupting the layout
420 $attr = preg_replace( '/<[^>]+>/', '', $attr );
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();
448 wfProfileOut( __METHOD__
);
453 * Translate a string to a variant.
454 * Doesn't parse rules or do any of that other stuff, for that use
455 * convert() or convertTo().
457 * @param string $text Text to convert
458 * @param string $variant Variant language code
459 * @return string Translated text
461 public function translate( $text, $variant ) {
462 wfProfileIn( __METHOD__
);
463 // If $text is empty or only includes spaces, do nothing
464 // Otherwise translate it
465 if ( trim( $text ) ) {
467 $text = $this->mTables
[$variant]->replace( $text );
469 wfProfileOut( __METHOD__
);
474 * Call translate() to convert text to all valid variants.
476 * @param string $text The text to be converted
477 * @return array Variant => converted text
479 public function autoConvertToAllVariants( $text ) {
480 wfProfileIn( __METHOD__
);
484 foreach ( $this->mVariants
as $variant ) {
485 $ret[$variant] = $this->translate( $text, $variant );
488 wfProfileOut( __METHOD__
);
493 * Apply manual conversion rules.
495 * @param $convRule ConverterRule Object of ConverterRule
497 protected function applyManualConv( $convRule ) {
498 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
500 // Bug 24072: $mConvRuleTitle was overwritten by other manual
501 // rule(s) not for title, this breaks the title conversion.
502 $newConvRuleTitle = $convRule->getTitle();
503 if ( $newConvRuleTitle ) {
504 // So I add an empty check for getTitle()
505 $this->mConvRuleTitle
= $newConvRuleTitle;
508 // merge/remove manual conversion rules to/from global table
509 $convTable = $convRule->getConvTable();
510 $action = $convRule->getRulesAction();
511 foreach ( $convTable as $variant => $pair ) {
512 if ( !$this->validateVariant( $variant ) ) {
516 if ( $action == 'add' ) {
517 foreach ( $pair as $from => $to ) {
518 // to ensure that $from and $to not be left blank
519 // so $this->translate() could always return a string
520 if ( $from ||
$to ) {
521 // more efficient than array_merge(), about 2.5 times.
522 $this->mTables
[$variant]->setPair( $from, $to );
525 } elseif ( $action == 'remove' ) {
526 $this->mTables
[$variant]->removeArray( $pair );
532 * Auto convert a Title object to a readable string in the
535 * @param Title $title A object of Title
536 * @return string Converted title text
538 public function convertTitle( $title ) {
539 $variant = $this->getPreferredVariant();
540 $index = $title->getNamespace();
541 if ( $index !== NS_MAIN
) {
542 $text = $this->convertNamespace( $index, $variant ) . ':';
546 $text .= $this->translate( $title->getText(), $variant );
551 * Get the namespace display name in the preferred variant.
553 * @param int $index Namespace id
554 * @param string|null $variant Variant code or null for preferred variant
555 * @return string Namespace name for display
557 public function convertNamespace( $index, $variant = null ) {
558 if ( $variant === null ) {
559 $variant = $this->getPreferredVariant();
561 if ( $index === NS_MAIN
) {
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 return $nsConvMsg->plain();
569 // Then check if a message gives a converted name in content language
570 // which needs extra translation to the target variant.
571 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
572 if ( $nsConvMsg->exists() ) {
573 return $this->translate( $nsConvMsg->plain(), $variant );
575 // No message exists, retrieve it from the target variant's namespace names.
576 $langObj = $this->mLangObj
->factory( $variant );
577 return $langObj->getFormattedNsText( $index );
582 * Convert text to different variants of a language. The automatic
583 * conversion is done in autoConvert(). Here we parse the text
584 * marked with -{}-, which specifies special conversions of the
585 * text that can not be accomplished in autoConvert().
587 * Syntax of the markup:
588 * -{code1:text1;code2:text2;...}- or
589 * -{flags|code1:text1;code2:text2;...}- or
590 * -{text}- in which case no conversion should take place for text
592 * @param string $text Text to be converted
593 * @return string Converted text
595 public function convert( $text ) {
596 $variant = $this->getPreferredVariant();
597 return $this->convertTo( $text, $variant );
601 * Same as convert() except a extra parameter to custom variant.
603 * @param string $text Text to be converted
604 * @param string $variant The target variant code
605 * @return string Converted text
607 public function convertTo( $text, $variant ) {
608 global $wgDisableLangConversion;
609 if ( $wgDisableLangConversion ) {
612 // Reset converter state for a new converter run.
613 $this->mConvRuleTitle
= false;
614 return $this->recursiveConvertTopLevel( $text, $variant );
618 * Recursively convert text on the outside. Allow to use nested
619 * markups to custom rules.
621 * @param string $text Text to be converted
622 * @param string $variant The target variant code
623 * @param int $depth Depth of recursion
624 * @return string Converted text
626 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
629 $length = strlen( $text );
630 $shouldConvert = !$this->guessVariant( $text, $variant );
632 while ( $startPos < $length ) {
633 $pos = strpos( $text, '-{', $startPos );
635 if ( $pos === false ) {
636 // No more markup, append final segment
637 $fragment = substr( $text, $startPos );
638 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
643 // Append initial segment
644 $fragment = substr( $text, $startPos, $pos - $startPos );
645 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
650 // Do recursive conversion
651 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
658 * Recursively convert text on the inside.
660 * @param string $text Text to be converted
661 * @param string $variant The target variant code
662 * @param int $startPos
663 * @param int $depth Depth of recursion
665 * @throws MWException
666 * @return string Converted text
668 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
669 // Quick sanity check (no function calls)
670 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
671 throw new MWException( __METHOD__
. ': invalid input string' );
676 $warningDone = false;
677 $length = strlen( $text );
679 while ( $startPos < $length ) {
681 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
691 // Append initial segment
692 $inner .= substr( $text, $startPos, $pos - $startPos );
700 if ( $depth >= $this->mMaxDepth
) {
702 if ( !$warningDone ) {
703 $inner .= '<span class="error">' .
704 wfMessage( 'language-converter-depth-warning' )
705 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
712 // Recursively parse another rule
713 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
718 $rule = new ConverterRule( $inner, $this );
719 $rule->parse( $variant );
720 $this->applyManualConv( $rule );
721 return $rule->getDisplay();
723 throw new MWException( __METHOD__
. ': invalid regex match' );
728 if ( $startPos < $length ) {
729 $inner .= substr( $text, $startPos );
732 return '-{' . $this->autoConvert( $inner, $variant );
736 * If a language supports multiple variants, it is possible that
737 * non-existing link in one variant actually exists in another variant.
738 * This function tries to find it. See e.g. LanguageZh.php
740 * @param string $link The name of the link
741 * @param mixed $nt The title object of the link
742 * @param bool $ignoreOtherCond To disable other conditions when
743 * we need to transclude a template or update a category's link
744 * @return void Null, the input parameters may be modified upon return
746 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
747 # If the article has already existed, there is no need to
748 # check it again, otherwise it may cause a fault.
749 if ( is_object( $nt ) && $nt->exists() ) {
753 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
754 $isredir = $wgRequest->getText( 'redirect', 'yes' );
755 $action = $wgRequest->getText( 'action' );
756 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
757 $disableLinkConversion = $wgDisableLangConversion
758 ||
$wgDisableTitleConversion;
759 $linkBatch = new LinkBatch();
763 if ( $disableLinkConversion ||
764 ( !$ignoreOtherCond &&
767 ||
$action == 'submit'
768 ||
$linkconvert == 'no' ) ) ) {
772 if ( is_object( $nt ) ) {
773 $ns = $nt->getNamespace();
776 $variants = $this->autoConvertToAllVariants( $link );
777 if ( !$variants ) { // give up
783 foreach ( $variants as $v ) {
785 $varnt = Title
::newFromText( $v, $ns );
786 if ( !is_null( $varnt ) ) {
787 $linkBatch->addObj( $varnt );
793 // fetch all variants in single query
794 $linkBatch->execute();
796 foreach ( $titles as $varnt ) {
797 if ( $varnt->getArticleID() > 0 ) {
799 $link = $varnt->getText();
806 * Returns language specific hash options.
810 public function getExtraHashOptions() {
811 $variant = $this->getPreferredVariant();
812 return '!' . $variant;
816 * Guess if a text is written in a variant. This should be implemented in subclasses.
818 * @param string $text the text to be checked
819 * @param string $variant language code of the variant to be checked for
820 * @return bool true if $text appears to be written in $variant, false if not
822 * @author Nikola Smolenski <smolensk@eunet.rs>
825 public function guessVariant( $text, $variant ) {
830 * Load default conversion tables.
831 * This method must be implemented in derived class.
834 * @throws MWException
836 function loadDefaultTables() {
837 $name = get_class( $this );
838 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
842 * Load conversion tables either from the cache or the disk.
844 * @param bool $fromCache Load from memcached? Defaults to true.
846 function loadTables( $fromCache = true ) {
847 global $wgLangConvMemc;
849 if ( $this->mTablesLoaded
) {
853 wfProfileIn( __METHOD__
);
854 $this->mTablesLoaded
= true;
855 $this->mTables
= false;
857 wfProfileIn( __METHOD__
. '-cache' );
858 $this->mTables
= $wgLangConvMemc->get( $this->mCacheKey
);
859 wfProfileOut( __METHOD__
. '-cache' );
861 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
862 wfProfileIn( __METHOD__
. '-recache' );
863 // not in cache, or we need a fresh reload.
864 // We will first load the default tables
865 // then update them using things in MediaWiki:Conversiontable/*
866 $this->loadDefaultTables();
867 foreach ( $this->mVariants
as $var ) {
868 $cached = $this->parseCachedTable( $var );
869 $this->mTables
[$var]->mergeArray( $cached );
872 $this->postLoadTables();
873 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
875 $wgLangConvMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
876 wfProfileOut( __METHOD__
. '-recache' );
878 wfProfileOut( __METHOD__
);
882 * Hook for post processing after conversion tables are loaded.
884 function postLoadTables() { }
887 * Reload the conversion tables.
891 function reloadTables() {
892 if ( $this->mTables
) {
893 unset( $this->mTables
);
895 $this->mTablesLoaded
= false;
896 $this->loadTables( false );
900 * Parse the conversion table stored in the cache.
902 * The tables should be in blocks of the following form:
909 * To make the tables more manageable, subpages are allowed
910 * and will be parsed recursively if $recursive == true.
912 * @param string $code Language code
913 * @param string $subpage Subpage name
914 * @param bool $recursive Parse subpages recursively? Defaults to true.
918 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
919 static $parsed = array();
921 $key = 'Conversiontable/' . $code;
923 $key .= '/' . $subpage;
925 if ( array_key_exists( $key, $parsed ) ) {
929 $parsed[$key] = true;
931 if ( $subpage === '' ) {
932 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
935 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
936 if ( $title && $title->exists() ) {
937 $revision = Revision
::newFromTitle( $title );
939 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
940 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
943 // @todo in the future, use a specialized content model, perhaps based on json!
948 # Nothing to parse if there's no text
949 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
953 // get all subpage links of the form
954 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
955 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
957 $subs = StringUtils
::explode( '[[', $txt );
959 foreach ( $subs as $sub ) {
960 $link = explode( ']]', $sub, 2 );
961 if ( count( $link ) != 2 ) {
964 $b = explode( '|', $link[0], 2 );
965 $b = explode( '/', trim( $b[0] ), 3 );
966 if ( count( $b ) == 3 ) {
972 if ( $b[0] == $linkhead && $b[1] == $code ) {
973 $sublinks[] = $sublink;
977 // parse the mappings in this page
978 $blocks = StringUtils
::explode( '-{', $txt );
981 foreach ( $blocks as $block ) {
983 // Skip the part before the first -{
987 $mappings = explode( '}-', $block, 2 );
988 $stripped = str_replace( array( "'", '"', '*', '#' ), '', $mappings[0] );
989 $table = StringUtils
::explode( ';', $stripped );
990 foreach ( $table as $t ) {
991 $m = explode( '=>', $t, 3 );
992 if ( count( $m ) != 2 ) {
995 // trim any trailling comments starting with '//'
996 $tt = explode( '//', $m[1], 2 );
997 $ret[trim( $m[0] )] = trim( $tt[0] );
1001 // recursively parse the subpages
1003 foreach ( $sublinks as $link ) {
1004 $s = $this->parseCachedTable( $code, $link, $recursive );
1005 $ret = array_merge( $ret, $s );
1009 if ( $this->mUcfirst
) {
1010 foreach ( $ret as $k => $v ) {
1011 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1018 * Enclose a string with the "no conversion" tag. This is used by
1019 * various functions in the Parser.
1021 * @param string $text Text to be tagged for no conversion
1022 * @param bool $noParse Unused
1023 * @return string The tagged text
1025 public function markNoConversion( $text, $noParse = false ) {
1026 # don't mark if already marked
1027 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1031 $ret = "-{R|$text}-";
1036 * Convert the sorting key for category links. This should make different
1037 * keys that are variants of each other map to the same key.
1039 * @param $key string
1043 function convertCategoryKey( $key ) {
1048 * Hook to refresh the cache of conversion tables when
1049 * MediaWiki:Conversiontable* is updated.
1052 * @param WikiPage $page
1053 * @param User $user User object for the current user
1054 * @param Content $content new page content
1055 * @param string $summary edit summary of the edit
1056 * @param bool $isMinor was the edit marked as minor?
1057 * @param bool $isWatch did the user watch this page or not?
1058 * @param string|int $section
1059 * @param int $flags Bitfield
1060 * @param Revision $revision new Revision object or null
1063 function OnPageContentSaveComplete( $page, $user, $content, $summary, $isMinor,
1064 $isWatch, $section, $flags, $revision ) {
1065 $titleobj = $page->getTitle();
1066 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1067 $title = $titleobj->getDBkey();
1068 $t = explode( '/', $title, 3 );
1070 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1071 if ( $this->validateVariant( $t[1] ) ) {
1072 $this->reloadTables();
1080 * Armour rendered math against conversion.
1081 * Escape special chars in parsed math text. (in most cases are img elements)
1083 * @param string $text Text to armour against conversion
1084 * @return string Armoured text where { and } have been converted to
1086 * @deprecated since 1.22 is no longer used
1088 public function armourMath( $text ) {
1089 // convert '-{' and '}-' to '-{' and '}-' to prevent
1090 // any unwanted markup appearing in the math image tag.
1091 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
1096 * Get the cached separator pattern for ConverterRule::parseRules()
1098 function getVarSeparatorPattern() {
1099 if ( is_null( $this->mVarSeparatorPattern
) ) {
1100 // varsep_pattern for preg_split:
1101 // text should be splited by ";" only if a valid variant
1102 // name exist after the markup, for example:
1103 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1104 // <span style="font-size:120%;">yyy</span>;}-
1105 // we should split it as:
1107 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1108 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1112 foreach ( $this->mVariants
as $variant ) {
1113 // zh-hans:xxx;zh-hant:yyy
1114 $pat .= $variant . '\s*:|';
1115 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1116 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1119 $this->mVarSeparatorPattern
= $pat;
1121 return $this->mVarSeparatorPattern
;