3 * Contains the LanguageConverter class and ConverterRule class
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Base class for language conversion.
28 * @author Zhengzhu Feng <zhengzhu@gmail.com>
29 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>, PhiLiP <philip.npc@gmail.com>
31 class LanguageConverter {
32 var $mMainLanguageCode;
33 var $mVariants, $mVariantFallbacks, $mVariantNames;
34 var $mTablesLoaded = false;
36 // 'bidirectional' 'unidirectional' 'disable' for each variant
41 var $mDescCodeSep = ':', $mDescVarSep = ';';
42 var $mUcfirst = false;
43 var $mConvRuleTitle = false;
48 var $mVarSeparatorPattern;
50 const CACHE_VERSION_KEY = 'VERSION 6';
55 * @param $langobj The Language Object
56 * @param $maincode String: the main language code of this language
57 * @param $variants Array: the supported variants of this language
58 * @param $variantfallbacks Array: the fallback language of each variant
59 * @param $flags Array: defining the custom strings that maps to the flags
60 * @param $manualLevel Array: limit for supported variants
62 public function __construct( $langobj, $maincode,
64 $variantfallbacks = array(),
66 $manualLevel = array() ) {
67 global $wgDisabledVariants, $wgLanguageNames;
68 $this->mLangObj = $langobj;
69 $this->mMainLanguageCode = $maincode;
70 $this->mVariants = array_diff( $variants, $wgDisabledVariants );
71 $this->mVariantFallbacks = $variantfallbacks;
72 $this->mVariantNames = $wgLanguageNames;
73 $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
74 $defaultflags = array(
75 // 'S' show converted text
76 // '+' add rules for alltext
77 // 'E' the gave flags is error
78 // these flags above are reserved for program
79 'A' => 'A', // add rule for convert code (all text convert)
80 'T' => 'T', // title convert
81 'R' => 'R', // raw content
82 'D' => 'D', // convert description (subclass implement)
83 '-' => '-', // remove convert (not implement)
84 'H' => 'H', // add rule for convert code
85 // (but no display in placed code )
86 'N' => 'N' // current variant name
88 $this->mFlags = array_merge( $defaultflags, $flags );
89 foreach ( $this->mVariants as $v ) {
90 if ( array_key_exists( $v, $manualLevel ) ) {
91 $this->mManualLevel[$v] = $manualLevel[$v];
93 $this->mManualLevel[$v] = 'bidirectional';
95 $this->mFlags[$v] = $v;
100 * Get all valid variants.
101 * Call this instead of using $this->mVariants directly.
103 * @return Array: contains all valid variants
105 public function getVariants() {
106 return $this->mVariants;
110 * In case some variant is not defined in the markup, we need
111 * to have some fallback. For example, in zh, normally people
112 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
113 * when zh-sg is preferred but not defined, we will pick zh-hans
114 * in this case. Right now this is only used by zh.
116 * @param $variant String: the language code of the variant
117 * @return String: The code of the fallback language or the
118 * main code if there is no fallback
120 public function getVariantFallbacks( $variant ) {
121 if ( isset( $this->mVariantFallbacks[$variant] ) ) {
122 return $this->mVariantFallbacks[$variant];
124 return $this->mMainLanguageCode;
128 * Get the title produced by the conversion rule.
129 * @return String: The converted title text
131 public function getConvRuleTitle() {
132 return $this->mConvRuleTitle;
136 * Get preferred language variant.
137 * @return String: the preferred language code
139 public function getPreferredVariant() {
140 global $wgDefaultLanguageVariant, $wgUser;
142 $req = $this->getURLVariant();
144 if ( $wgUser->isLoggedIn() && !$req ) {
145 $req = $this->getUserVariant();
149 $req = $this->getHeaderVariant();
152 if ( $wgDefaultLanguageVariant && !$req ) {
153 $req = $this->validateVariant( $wgDefaultLanguageVariant );
156 // This function, unlike the other get*Variant functions, is
157 // not memoized (i.e. there return value is not cached) since
158 // new information might appear during processing after this
163 return $this->mMainLanguageCode;
167 * Get default variant.
168 * This function would not be affected by user's settings or headers
169 * @return String: the default variant code
171 public function getDefaultVariant() {
172 global $wgDefaultLanguageVariant;
174 $req = $this->getURLVariant();
176 if ( $wgDefaultLanguageVariant && !$req ) {
177 $req = $this->validateVariant( $wgDefaultLanguageVariant );
183 return $this->mMainLanguageCode;
187 * Validate the variant
188 * @param $variant String: the variant to validate
189 * @return Mixed: returns the variant if it is valid, null otherwise
191 protected function validateVariant( $variant = null ) {
192 if ( $variant !== null &&
193 in_array( $variant, $this->mVariants ) ) {
200 * Get the variant specified in the URL
202 * @return Mixed: variant if one found, false otherwise.
204 public function getURLVariant() {
207 if ( $this->mURLVariant ) {
208 return $this->mURLVariant;
211 // see if the preference is set in the request
212 $ret = $wgRequest->getText( 'variant' );
215 $ret = $wgRequest->getVal( 'uselang' );
218 return $this->mURLVariant = $this->validateVariant( $ret );
222 * Determine if the user has a variant set.
224 * @return Mixed: variant if one found, false otherwise.
226 protected function getUserVariant() {
229 // memoizing this function wreaks havoc on parserTest.php
230 /* if ( $this->mUserVariant ) { */
231 /* return $this->mUserVariant; */
234 // get language variant preference from logged in users
235 // Don't call this on stub objects because that causes infinite
236 // recursion during initialisation
237 if ( $wgUser->isLoggedIn() ) {
238 $ret = $wgUser->getOption( 'variant' );
241 // figure out user lang without constructing wgLang to avoid
242 // infinite recursion
243 $ret = $wgUser->getOption( 'language' );
246 return $this->mUserVariant = $this->validateVariant( $ret );
250 * Determine the language variant from the Accept-Language header.
252 * @return Mixed: variant if one found, false otherwise.
254 protected function getHeaderVariant() {
257 if ( $this->mHeaderVariant ) {
258 return $this->mHeaderVariant;
261 // see if some supported language variant is set in the
263 $languages = array_keys( $wgRequest->getAcceptLang() );
264 if ( empty( $languages ) ) {
268 $fallback_languages = array();
269 foreach ( $languages as $language ) {
270 $this->mHeaderVariant = $this->validateVariant( $language );
271 if ( $this->mHeaderVariant ) {
275 // To see if there are fallbacks of current language.
276 // We record these fallback variants, and process
278 $fallbacks = $this->getVariantFallbacks( $language );
279 if ( is_string( $fallbacks ) ) {
280 $fallback_languages[] = $fallbacks;
281 } elseif ( is_array( $fallbacks ) ) {
282 $fallback_languages =
283 array_merge( $fallback_languages,
288 if ( !$this->mHeaderVariant ) {
289 // process fallback languages now
290 $fallback_languages = array_unique( $fallback_languages );
291 foreach ( $fallback_languages as $language ) {
292 $this->mHeaderVariant = $this->validateVariant( $language );
293 if ( $this->mHeaderVariant ) {
299 return $this->mHeaderVariant;
303 * Dictionary-based conversion.
304 * This function would not parse the conversion rules.
305 * If you want to parse rules, try to use convert() or
308 * @param $text String: the text to be converted
309 * @param $toVariant String: the target language code
310 * @return String: the converted text
312 public function autoConvert( $text, $toVariant = false ) {
313 wfProfileIn( __METHOD__ );
318 $toVariant = $this->getPreferredVariant();
320 wfProfileOut( __METHOD__ );
325 /* we convert everything except:
326 1. html markups (anything between < and >)
328 3. place holders created by the parser
331 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
332 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
337 // this one is needed when the text is inside an html markup
338 $htmlfix = '|<[^>]+$|^[^<>]*>';
340 // disable convert to variants between <code></code> tags
341 $codefix = '<code>.+?<\/code>|';
342 // disable convertsion of <script type="text/javascript"> ... </script>
343 $scriptfix = '<script.*?>.*?<\/script>|';
344 // disable conversion of <pre xxxx> ... </pre>
345 $prefix = '<pre.*?>.*?<\/pre>|';
347 $reg = '/' . $codefix . $scriptfix . $prefix .
348 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
353 // Guard against delimiter nulls in the input
354 $text = str_replace( "\000", '', $text );
356 while ( $startPos < strlen( $text ) ) {
357 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
358 $elementPos = $markupMatches[0][1];
359 $element = $markupMatches[0][0];
361 $elementPos = strlen( $text );
365 // Queue the part before the markup for translation in a batch
366 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
368 // Advance to the next position
369 $startPos = $elementPos + strlen( $element );
371 // Translate any alt or title attributes inside the matched element
372 if ( $element !== '' && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element,
375 $attrs = Sanitizer::decodeTagAttributes( $elementMatches[2] );
377 foreach ( array( 'title', 'alt' ) as $attrName ) {
378 if ( !isset( $attrs[$attrName] ) ) {
381 $attr = $attrs[$attrName];
382 // Don't convert URLs
383 if ( !strpos( $attr, '://' ) ) {
384 $attr = $this->translate( $attr, $toVariant );
387 // Remove HTML tags to avoid disrupting the layout
388 $attr = preg_replace( '/<[^>]+>/', '', $attr );
389 if ( $attr !== $attrs[$attrName] ) {
390 $attrs[$attrName] = $attr;
395 $element = $elementMatches[1] . Html::expandAttributes( $attrs ) .
399 $literalBlob .= $element . "\000";
402 // Do the main translation batch
403 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
405 // Put the output back together
406 $translatedIter = StringUtils::explode( "\000", $translatedBlob );
407 $literalIter = StringUtils::explode( "\000", $literalBlob );
409 while ( $translatedIter->valid() && $literalIter->valid() ) {
410 $output .= $translatedIter->current();
411 $output .= $literalIter->current();
412 $translatedIter->next();
413 $literalIter->next();
416 wfProfileOut( __METHOD__ );
421 * Translate a string to a variant.
422 * Doesn't parse rules or do any of that other stuff, for that use
423 * convert() or convertTo().
425 * @param $text String: text to convert
426 * @param $variant String: variant language code
427 * @return String: translated text
429 public function translate( $text, $variant ) {
430 wfProfileIn( __METHOD__ );
431 // If $text is empty or only includes spaces, do nothing
432 // Otherwise translate it
433 if ( trim( $text ) ) {
435 $text = $this->mTables[$variant]->replace( $text );
437 wfProfileOut( __METHOD__ );
442 * Call translate() to convert text to all valid variants.
444 * @param $text String: the text to be converted
445 * @return Array: variant => converted text
447 public function autoConvertToAllVariants( $text ) {
448 wfProfileIn( __METHOD__ );
452 foreach ( $this->mVariants as $variant ) {
453 $ret[$variant] = $this->translate( $text, $variant );
456 wfProfileOut( __METHOD__ );
461 * Convert link text to all valid variants.
462 * In the first, this function only convert text outside the
463 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
464 * titles, the text will get all converted always.
465 * So I removed this feature and deprecated the function.
467 * @param $text String: the text to be converted
468 * @return Array: variant => converted text
469 * @deprecated Use autoConvertToAllVariants() instead
471 public function convertLinkToAllVariants( $text ) {
472 return $this->autoConvertToAllVariants( $text );
476 * Apply manual conversion rules.
478 * @param $convRule Object: Object of ConverterRule
480 protected function applyManualConv( $convRule ) {
481 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
483 // Bug 24072: $mConvRuleTitle was overwritten by other manual
484 // rule(s) not for title, this breaks the title conversion.
485 $newConvRuleTitle = $convRule->getTitle();
486 if ( $newConvRuleTitle ) {
487 // So I add an empty check for getTitle()
488 $this->mConvRuleTitle = $newConvRuleTitle;
491 // merge/remove manual conversion rules to/from global table
492 $convTable = $convRule->getConvTable();
493 $action = $convRule->getRulesAction();
494 foreach ( $convTable as $variant => $pair ) {
495 if ( !$this->validateVariant( $variant ) ) {
499 if ( $action == 'add' ) {
500 foreach ( $pair as $from => $to ) {
501 // to ensure that $from and $to not be left blank
502 // so $this->translate() could always return a string
503 if ( $from || $to ) {
504 // more efficient than array_merge(), about 2.5 times.
505 $this->mTables[$variant]->setPair( $from, $to );
508 } elseif ( $action == 'remove' ) {
509 $this->mTables[$variant]->removeArray( $pair );
515 * Auto convert a Title object to a readable string in the
518 *@param $title Object: a object of Title
519 *@return String: converted title text
521 public function convertTitle( $title ) {
522 $variant = $this->getPreferredVariant();
523 $index = $title->getNamespace();
524 if ( $index === NS_MAIN ) {
527 // first let's check if a message has given us a converted name
528 $nsConvKey = 'conversion-ns' . $index;
529 if ( !wfEmptyMsg( $nsConvKey ) ) {
530 $text = wfMsgForContentNoTrans( $nsConvKey );
532 // the message does not exist, try retrieve it from the current
533 // variant's namespace names.
534 $langObj = $this->mLangObj->factory( $variant );
535 $text = $langObj->getFormattedNsText( $index );
539 $text .= $title->getText();
540 $text = $this->translate( $text, $variant );
545 * Convert text to different variants of a language. The automatic
546 * conversion is done in autoConvert(). Here we parse the text
547 * marked with -{}-, which specifies special conversions of the
548 * text that can not be accomplished in autoConvert().
550 * Syntax of the markup:
551 * -{code1:text1;code2:text2;...}- or
552 * -{flags|code1:text1;code2:text2;...}- or
553 * -{text}- in which case no conversion should take place for text
555 * @param $text String: text to be converted
556 * @return String: converted text
558 public function convert( $text ) {
559 $variant = $this->getPreferredVariant();
560 return $this->convertTo( $text, $variant );
564 * Same as convert() except a extra parameter to custom variant.
566 * @param $text String: text to be converted
567 * @param $variant String: the target variant code
568 * @return String: converted text
570 public function convertTo( $text, $variant ) {
571 global $wgDisableLangConversion;
572 if ( $wgDisableLangConversion ) return $text;
573 return $this->recursiveConvertTopLevel( $text, $variant );
577 * Recursively convert text on the outside. Allow to use nested
578 * markups to custom rules.
580 * @param $text String: text to be converted
581 * @param $variant String: the target variant code
582 * @param $depth Integer: depth of recursion
583 * @return String: converted text
585 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
588 $length = strlen( $text );
589 while ( $startPos < $length ) {
590 $pos = strpos( $text, '-{', $startPos );
592 if ( $pos === false ) {
593 // No more markup, append final segment
594 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
599 // Append initial segment
600 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
605 // Do recursive conversion
606 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
613 * Recursively convert text on the inside.
615 * @param $text String: text to be converted
616 * @param $variant String: the target variant code
617 * @param $depth Integer: depth of recursion
618 * @return String: converted text
620 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
621 // Quick sanity check (no function calls)
622 if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
623 throw new MWException( __METHOD__ . ': invalid input string' );
628 $warningDone = false;
629 $length = strlen( $text );
631 while ( $startPos < $length ) {
633 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
643 // Append initial segment
644 $inner .= substr( $text, $startPos, $pos - $startPos );
652 if ( $depth >= $this->mMaxDepth ) {
654 if ( !$warningDone ) {
655 $inner .= '<span class="error">' .
656 wfMsgForContent( 'language-converter-depth-warning',
664 // Recursively parse another rule
665 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
670 $rule = new ConverterRule( $inner, $this );
671 $rule->parse( $variant );
672 $this->applyManualConv( $rule );
673 return $rule->getDisplay();
675 throw new MWException( __METHOD__ . ': invalid regex match' );
680 if ( $startPos < $length ) {
681 $inner .= substr( $text, $startPos );
684 return '-{' . $this->autoConvert( $inner, $variant );
688 * If a language supports multiple variants, it is
689 * possible that non-existing link in one variant
690 * actually exists in another variant. This function
691 * tries to find it. See e.g. LanguageZh.php
693 * @param $link String: the name of the link
694 * @param $nt Mixed: the title object of the link
695 * @param $ignoreOtherCond Boolean: to disable other conditions when
696 * we need to transclude a template or update a category's link
697 * @return Null, the input parameters may be modified upon return
699 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
700 # If the article has already existed, there is no need to
701 # check it again, otherwise it may cause a fault.
702 if ( is_object( $nt ) && $nt->exists() ) {
706 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
708 $isredir = $wgRequest->getText( 'redirect', 'yes' );
709 $action = $wgRequest->getText( 'action' );
710 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
711 $disableLinkConversion = $wgDisableLangConversion
712 || $wgDisableTitleConversion;
713 $linkBatch = new LinkBatch();
717 if ( $disableLinkConversion ||
718 ( !$ignoreOtherCond &&
721 || $action == 'submit'
722 || $linkconvert == 'no'
723 || $wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
727 if ( is_object( $nt ) ) {
728 $ns = $nt->getNamespace();
731 $variants = $this->autoConvertToAllVariants( $link );
732 if ( !$variants ) { // give up
738 foreach ( $variants as $v ) {
740 $varnt = Title::newFromText( $v, $ns );
741 if ( !is_null( $varnt ) ) {
742 $linkBatch->addObj( $varnt );
748 // fetch all variants in single query
749 $linkBatch->execute();
751 foreach ( $titles as $varnt ) {
752 if ( $varnt->getArticleID() > 0 ) {
754 $link = $varnt->getText();
761 * Returns language specific hash options.
763 public function getExtraHashOptions() {
764 $variant = $this->getPreferredVariant();
765 return '!' . $variant ;
769 * Load default conversion tables.
770 * This method must be implemented in derived class.
774 function loadDefaultTables() {
775 $name = get_class( $this );
776 wfDie( "Must implement loadDefaultTables() method in class $name" );
780 * Load conversion tables either from the cache or the disk.
783 function loadTables( $fromcache = true ) {
784 if ( $this->mTablesLoaded ) {
788 wfProfileIn( __METHOD__ );
789 $this->mTablesLoaded = true;
790 $this->mTables = false;
792 wfProfileIn( __METHOD__ . '-cache' );
793 $this->mTables = $wgMemc->get( $this->mCacheKey );
794 wfProfileOut( __METHOD__ . '-cache' );
797 || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
798 wfProfileIn( __METHOD__ . '-recache' );
799 // not in cache, or we need a fresh reload.
800 // we will first load the default tables
801 // then update them using things in MediaWiki:Zhconversiontable/*
802 $this->loadDefaultTables();
803 foreach ( $this->mVariants as $var ) {
804 $cached = $this->parseCachedTable( $var );
805 $this->mTables[$var]->mergeArray( $cached );
808 $this->postLoadTables();
809 $this->mTables[self::CACHE_VERSION_KEY] = true;
811 $wgMemc->set( $this->mCacheKey, $this->mTables, 43200 );
812 wfProfileOut( __METHOD__ . '-recache' );
814 wfProfileOut( __METHOD__ );
818 * Hook for post processig after conversion tables are loaded.
821 function postLoadTables() { }
824 * Reload the conversion tables.
828 function reloadTables() {
829 if ( $this->mTables ) {
830 unset( $this->mTables );
832 $this->mTablesLoaded = false;
833 $this->loadTables( false );
838 * Parse the conversion table stored in the cache.
840 * The tables should be in blocks of the following form:
847 * To make the tables more manageable, subpages are allowed
848 * and will be parsed recursively if $recursive == true.
851 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
852 global $wgMessageCache;
853 static $parsed = array();
855 if ( !is_object( $wgMessageCache ) ) {
859 $key = 'Conversiontable/' . $code;
861 $key .= '/' . $subpage;
863 if ( array_key_exists( $key, $parsed ) ) {
867 if ( strpos( $code, '/' ) === false ) {
868 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
869 if ( $txt === false ) {
870 # FIXME: this method doesn't seem to be expecting
871 # this possible outcome...
872 $txt = '<Conversiontable>';
875 $title = Title::makeTitleSafe( NS_MEDIAWIKI,
876 "Conversiontable/$code" );
877 if ( $title && $title->exists() ) {
878 $article = new Article( $title );
879 $txt = $article->getContents();
885 // get all subpage links of the form
886 // [[MediaWiki:conversiontable/zh-xx/...|...]]
887 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
889 $subs = StringUtils::explode( '[[', $txt );
891 foreach ( $subs as $sub ) {
892 $link = explode( ']]', $sub, 2 );
893 if ( count( $link ) != 2 ) {
896 $b = explode( '|', $link[0], 2 );
897 $b = explode( '/', trim( $b[0] ), 3 );
898 if ( count( $b ) == 3 ) {
904 if ( $b[0] == $linkhead && $b[1] == $code ) {
905 $sublinks[] = $sublink;
909 // parse the mappings in this page
910 $blocks = StringUtils::explode( '-{', $txt );
913 foreach ( $blocks as $block ) {
915 // Skip the part before the first -{
919 $mappings = explode( '}-', $block, 2 );
920 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
922 $table = StringUtils::explode( ';', $stripped );
923 foreach ( $table as $t ) {
924 $m = explode( '=>', $t, 3 );
925 if ( count( $m ) != 2 )
927 // trim any trailling comments starting with '//'
928 $tt = explode( '//', $m[1], 2 );
929 $ret[trim( $m[0] )] = trim( $tt[0] );
932 $parsed[$key] = true;
934 // recursively parse the subpages
936 foreach ( $sublinks as $link ) {
937 $s = $this->parseCachedTable( $code, $link, $recursive );
938 $ret = array_merge( $ret, $s );
942 if ( $this->mUcfirst ) {
943 foreach ( $ret as $k => $v ) {
944 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
951 * Enclose a string with the "no conversion" tag. This is used by
952 * various functions in the Parser.
954 * @param $text String: text to be tagged for no conversion
955 * @param $noParse Unused (?)
956 * @return String: the tagged text
958 public function markNoConversion( $text, $noParse = false ) {
959 # don't mark if already marked
960 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
964 $ret = "-{R|$text}-";
969 * Convert the sorting key for category links. This should make different
970 * keys that are variants of each other map to the same key.
972 function convertCategoryKey( $key ) {
977 * Hook to refresh the cache of conversion tables when
978 * MediaWiki:conversiontable* is updated.
981 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
982 $iswatch, $section, $flags, $revision ) {
983 $titleobj = $article->getTitle();
984 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
985 $title = $titleobj->getDBkey();
986 $t = explode( '/', $title, 3 );
988 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
989 if ( $this->validateVariant( $t[1] ) ) {
990 $this->reloadTables();
998 * Armour rendered math against conversion.
999 * Escape special chars in parsed math text.(in most cases are img elements)
1001 public function armourMath( $text ) {
1002 // convert '-{' and '}-' to '-{' and '}-' to prevent
1003 // any unwanted markup appearing in the math image tag.
1004 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
1009 * Get the cached separator pattern for ConverterRule::parseRules()
1011 function getVarSeparatorPattern() {
1012 if ( is_null( $this->mVarSeparatorPattern ) ) {
1013 // varsep_pattern for preg_split:
1014 // text should be splited by ";" only if a valid variant
1015 // name exist after the markup, for example:
1016 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1017 // <span style="font-size:120%;">yyy</span>;}-
1018 // we should split it as:
1020 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1021 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1025 foreach ( $this->mVariants as $variant ) {
1026 // zh-hans:xxx;zh-hant:yyy
1027 $pat .= $variant . '\s*:|';
1028 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1029 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1032 $this->mVarSeparatorPattern = $pat;
1034 return $this->mVarSeparatorPattern;
1039 * Parser for rules of language conversion , parse rules in -{ }- tag.
1041 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1043 class ConverterRule {
1044 var $mText; // original text in -{text}-
1045 var $mConverter; // LanguageConverter object
1046 var $mManualCodeError = '<strong class="error">code error!</strong>';
1047 var $mRuleDisplay = '';
1048 var $mRuleTitle = false;
1049 var $mRules = '';// string : the text of the rules
1050 var $mRulesAction = 'none';
1051 var $mFlags = array();
1052 var $mVariantFlags = array();
1053 var $mConvTable = array();
1054 var $mBidtable = array();// array of the translation in each variant
1055 var $mUnidtable = array();// array of the translation in each variant
1060 * @param $text String: the text between -{ and }-
1061 * @param $converter LanguageConverter object
1063 public function __construct( $text, $converter ) {
1064 $this->mText = $text;
1065 $this->mConverter = $converter;
1069 * Check if variants array in convert array.
1071 * @param $variants Array or string: variant language code
1072 * @return String: translated text
1074 public function getTextInBidtable( $variants ) {
1075 $variants = (array)$variants;
1079 foreach ( $variants as $variant ) {
1080 if ( isset( $this->mBidtable[$variant] ) ) {
1081 return $this->mBidtable[$variant];
1088 * Parse flags with syntax -{FLAG| ... }-
1091 function parseFlags() {
1092 $text = $this->mText;
1094 $variantFlags = array();
1096 $sepPos = strpos( $text, '|' );
1097 if ( $sepPos !== false ) {
1098 $validFlags = $this->mConverter->mFlags;
1099 $f = StringUtils::explode( ';', substr( $text, 0, $sepPos ) );
1100 foreach ( $f as $ff ) {
1102 if ( isset( $validFlags[$ff] ) ) {
1103 $flags[$validFlags[$ff]] = true;
1106 $text = strval( substr( $text, $sepPos + 1 ) );
1111 } elseif ( isset( $flags['R'] ) ) {
1112 $flags = array( 'R' => true );// remove other flags
1113 } elseif ( isset( $flags['N'] ) ) {
1114 $flags = array( 'N' => true );// remove other flags
1115 } elseif ( isset( $flags['-'] ) ) {
1116 $flags = array( '-' => true );// remove other flags
1117 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1119 } elseif ( isset( $flags['H'] ) ) {
1120 // replace A flag, and remove other flags except T
1121 $temp = array( '+' => true, 'H' => true );
1122 if ( isset( $flags['T'] ) ) {
1125 if ( isset( $flags['D'] ) ) {
1130 if ( isset( $flags['A'] ) ) {
1134 if ( isset( $flags['D'] ) ) {
1135 unset( $flags['S'] );
1137 // try to find flags like "zh-hans", "zh-hant"
1138 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1139 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter->mVariants );
1140 if ( $variantFlags ) {
1141 $variantFlags = array_flip( $variantFlags );
1145 $this->mVariantFlags = $variantFlags;
1146 $this->mRules = $text;
1147 $this->mFlags = $flags;
1151 * Generate conversion table.
1154 function parseRules() {
1155 $rules = $this->mRules;
1156 $bidtable = array();
1157 $unidtable = array();
1158 $variants = $this->mConverter->mVariants;
1159 $varsep_pattern = $this->mConverter->getVarSeparatorPattern();
1161 $choice = preg_split( $varsep_pattern, $rules );
1163 foreach ( $choice as $c ) {
1164 $v = explode( ':', $c, 2 );
1165 if ( count( $v ) != 2 ) {
1166 // syntax error, skip
1169 $to = trim( $v[1] );
1171 $u = explode( '=>', $v, 2 );
1172 // if $to is empty, strtr() could return a wrong result
1173 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1174 $bidtable[$v] = $to;
1175 } elseif ( count( $u ) == 2 ) {
1176 $from = trim( $u[0] );
1178 if ( array_key_exists( $v, $unidtable )
1179 && !is_array( $unidtable[$v] )
1181 && in_array( $v, $variants ) ) {
1182 $unidtable[$v] = array( $from => $to );
1183 } elseif ( $to && in_array( $v, $variants ) ) {
1184 $unidtable[$v][$from] = $to;
1187 // syntax error, pass
1188 if ( !isset( $this->mConverter->mVariantNames[$v] ) ) {
1189 $bidtable = array();
1190 $unidtable = array();
1194 $this->mBidtable = $bidtable;
1195 $this->mUnidtable = $unidtable;
1201 function getRulesDesc() {
1202 $codesep = $this->mConverter->mDescCodeSep;
1203 $varsep = $this->mConverter->mDescVarSep;
1205 foreach ( $this->mBidtable as $k => $v ) {
1206 $text .= $this->mConverter->mVariantNames[$k] . "$codesep$v$varsep";
1208 foreach ( $this->mUnidtable as $k => $a ) {
1209 foreach ( $a as $from => $to ) {
1210 $text .= $from . '⇒' . $this->mConverter->mVariantNames[$k] .
1211 "$codesep$to$varsep";
1218 * Parse rules conversion.
1221 function getRuleConvertedStr( $variant ) {
1222 $bidtable = $this->mBidtable;
1223 $unidtable = $this->mUnidtable;
1225 if ( count( $bidtable ) + count( $unidtable ) == 0 ) {
1226 return $this->mRules;
1228 // display current variant in bidirectional array
1229 $disp = $this->getTextInBidtable( $variant );
1230 // or display current variant in fallbacks
1232 $disp = $this->getTextInBidtable(
1233 $this->mConverter->getVariantFallbacks( $variant ) );
1235 // or display current variant in unidirectional array
1236 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1237 $disp = array_values( $unidtable[$variant] );
1240 // or display frist text under disable manual convert
1242 && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
1243 if ( count( $bidtable ) > 0 ) {
1244 $disp = array_values( $bidtable );
1247 $disp = array_values( $unidtable );
1248 $disp = array_values( $disp[0] );
1257 * Generate conversion table for all text.
1260 function generateConvTable() {
1261 // Special case optimisation
1262 if ( !$this->mBidtable && !$this->mUnidtable ) {
1263 $this->mConvTable = array();
1267 $bidtable = $this->mBidtable;
1268 $unidtable = $this->mUnidtable;
1269 $manLevel = $this->mConverter->mManualLevel;
1272 foreach ( $this->mConverter->mVariants as $v ) {
1273 /* for bidirectional array
1274 fill in the missing variants, if any,
1276 if ( !isset( $bidtable[$v] ) ) {
1278 $this->mConverter->getVariantFallbacks( $v );
1279 $vf = $this->getTextInBidtable( $variantFallbacks );
1281 $bidtable[$v] = $vf;
1285 if ( isset( $bidtable[$v] ) ) {
1286 foreach ( $vmarked as $vo ) {
1287 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1288 // or -{H|zh:WordZh;zh-tw:WordTw}-
1289 // or -{-|zh:WordZh;zh-tw:WordTw}-
1290 // to introduce a custom mapping between
1291 // words WordZh and WordTw in the whole text
1292 if ( $manLevel[$v] == 'bidirectional' ) {
1293 $this->mConvTable[$v][$bidtable[$vo]] = $bidtable[$v];
1295 if ( $manLevel[$vo] == 'bidirectional' ) {
1296 $this->mConvTable[$vo][$bidtable[$v]] = $bidtable[$vo];
1301 /*for unidirectional array fill to convert tables */
1302 if ( ( $manLevel[$v] == 'bidirectional' || $manLevel[$v] == 'unidirectional' )
1303 && isset( $unidtable[$v] ) )
1305 if ( isset( $this->mConvTable[$v] ) ) {
1306 $this->mConvTable[$v] = array_merge( $this->mConvTable[$v], $unidtable[$v] );
1308 $this->mConvTable[$v] = $unidtable[$v];
1315 * Parse rules and flags.
1318 function parse( $variant = NULL ) {
1320 $variant = $this->mConverter->getPreferredVariant();
1323 $this->parseFlags();
1324 $flags = $this->mFlags;
1326 // convert to specified variant
1327 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1328 if ( $this->mVariantFlags ) {
1329 // check if current variant in flags
1330 if ( isset( $this->mVariantFlags[$variant] ) ) {
1331 // then convert <text to convert> to current language
1332 $this->mRules = $this->mConverter->autoConvert( $this->mRules,
1334 } else { // if current variant no in flags,
1335 // then we check its fallback variants.
1337 $this->mConverter->getVariantFallbacks( $variant );
1338 foreach ( $variantFallbacks as $variantFallback ) {
1339 // if current variant's fallback exist in flags
1340 if ( isset( $this->mVariantFlags[$variantFallback] ) ) {
1341 // then convert <text to convert> to fallback language
1343 $this->mConverter->autoConvert( $this->mRules,
1349 $this->mFlags = $flags = array( 'R' => true );
1352 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1353 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1354 $this->mRules = str_replace( '=>', '=>', $this->mRules );
1355 $this->parseRules();
1357 $rules = $this->mRules;
1359 if ( !$this->mBidtable && !$this->mUnidtable ) {
1360 if ( isset( $flags['+'] ) || isset( $flags['-'] ) ) {
1361 // fill all variants if text in -{A/H/-|text} without rules
1362 foreach ( $this->mConverter->mVariants as $v ) {
1363 $this->mBidtable[$v] = $rules;
1365 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1366 $this->mFlags = $flags = array( 'R' => true );
1370 $this->mRuleDisplay = false;
1371 foreach ( $flags as $flag => $unused ) {
1374 // if we don't do content convert, still strip the -{}- tags
1375 $this->mRuleDisplay = $rules;
1378 // process N flag: output current variant name
1379 $ruleVar = trim( $rules );
1380 if ( isset( $this->mConverter->mVariantNames[$ruleVar] ) ) {
1381 $this->mRuleDisplay = $this->mConverter->mVariantNames[$ruleVar];
1383 $this->mRuleDisplay = '';
1387 // process D flag: output rules description
1388 $this->mRuleDisplay = $this->getRulesDesc();
1391 // process H,- flag or T only: output nothing
1392 $this->mRuleDisplay = '';
1395 $this->mRulesAction = 'remove';
1396 $this->mRuleDisplay = '';
1399 $this->mRulesAction = 'add';
1400 $this->mRuleDisplay = '';
1403 $this->mRuleDisplay = $this->getRuleConvertedStr( $variant );
1406 $this->mRuleTitle = $this->getRuleConvertedStr( $variant );
1407 $this->mRuleDisplay = '';
1410 // ignore unknown flags (but see error case below)
1413 if ( $this->mRuleDisplay === false ) {
1414 $this->mRuleDisplay = $this->mManualCodeError;
1417 $this->generateConvTable();
1423 function hasRules() {
1428 * Get display text on markup -{...}-
1431 function getDisplay() {
1432 return $this->mRuleDisplay;
1436 * Get converted title.
1439 function getTitle() {
1440 return $this->mRuleTitle;
1444 * Return how deal with conversion rules.
1447 function getRulesAction() {
1448 return $this->mRulesAction;
1452 * Get conversion table. ( bidirectional and unidirectional
1453 * conversion table )
1456 function getConvTable() {
1457 return $this->mConvTable;
1461 * Get conversion rules string.
1464 function getRules() {
1465 return $this->mRules;
1469 * Get conversion flags.
1472 function getFlags() {
1473 return $this->mFlags;