4 * Contains the LanguageConverter class and ConverterRule class
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
12 * Base class for language conversion.
15 * @author Zhengzhu Feng <zhengzhu@gmail.com>
16 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>, PhiLiP <philip.npc@gmail.com>
18 class LanguageConverter {
19 var $mMainLanguageCode;
20 var $mVariants, $mVariantFallbacks, $mVariantNames;
21 var $mTablesLoaded = false;
23 // 'bidirectional' 'unidirectional' 'disable' for each variant
28 var $mDescCodeSep = ':', $mDescVarSep = ';';
29 var $mUcfirst = false;
30 var $mConvRuleTitle = false;
35 var $mVarSeparatorPattern;
37 const CACHE_VERSION_KEY = 'VERSION 6';
42 * @param $langobj The Language Object
43 * @param $maincode String: the main language code of this language
44 * @param $variants Array: the supported variants of this language
45 * @param $variantfallbacks Array: the fallback language of each variant
46 * @param $flags Array: defining the custom strings that maps to the flags
47 * @param $manualLevel Array: limit for supported variants
49 public function __construct( $langobj, $maincode,
51 $variantfallbacks = array(),
53 $manualLevel = array() ) {
54 $this->mLangObj = $langobj;
55 $this->mMainLanguageCode = $maincode;
57 global $wgDisabledVariants;
58 $this->mVariants = array();
59 foreach ( $variants as $variant ) {
60 if ( !in_array( $variant, $wgDisabledVariants ) ) {
61 $this->mVariants[] = $variant;
64 $this->mVariantFallbacks = $variantfallbacks;
65 global $wgLanguageNames;
66 $this->mVariantNames = $wgLanguageNames;
67 $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
69 // 'S' show converted text
70 // '+' add rules for alltext
71 // 'E' the gave flags is error
72 // these flags above are reserved for program
73 'A' => 'A', // add rule for convert code (all text convert)
74 'T' => 'T', // title convert
75 'R' => 'R', // raw content
76 'D' => 'D', // convert description (subclass implement)
77 '-' => '-', // remove convert (not implement)
78 'H' => 'H', // add rule for convert code
79 // (but no display in placed code )
80 'N' => 'N' // current variant name
82 $this->mFlags = array_merge( $f, $flags );
83 foreach ( $this->mVariants as $v ) {
84 if ( array_key_exists( $v, $manualLevel ) ) {
85 $this->mManualLevel[$v] = $manualLevel[$v];
87 $this->mManualLevel[$v] = 'bidirectional';
89 $this->mFlags[$v] = $v;
96 function getVariants() {
97 return $this->mVariants;
101 * In case some variant is not defined in the markup, we need
102 * to have some fallback. For example, in zh, normally people
103 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
104 * when zh-sg is preferred but not defined, we will pick zh-hans
105 * in this case. Right now this is only used by zh.
107 * @param string $v The language code of the variant
108 * @return string array The code of the fallback language or false if there
112 function getVariantFallbacks( $v ) {
113 if ( isset( $this->mVariantFallbacks[$v] ) ) {
114 return $this->mVariantFallbacks[$v];
116 return $this->mMainLanguageCode;
120 * Get the title produced by the conversion rule.
123 function getConvRuleTitle() {
124 return $this->mConvRuleTitle;
128 * Get preferred language variants.
129 * @param boolean $fromUser Get it from $wgUser's preferences
130 * @param boolean $fromHeader Get it from Accept-Language
131 * @return string the preferred language code
134 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
135 global $wgDefaultLanguageVariant;
137 $req = $this->getURLVariant();
139 if ( $fromUser && !$req ) {
140 $req = $this->getUserVariant();
143 if ( $fromHeader && !$req ) {
144 $req = $this->getHeaderVariant();
147 if ( $wgDefaultLanguageVariant && !$req ) {
148 $req = $this->validateVariant( $wgDefaultLanguageVariant );
151 // This function, unlike the other get*Variant functions, is
152 // not memoized (i.e. there return value is not cached) since
153 // new information might appear during processing after this
158 return $this->mMainLanguageCode;
162 * Validate the variant
163 * @param string $v the variant to validate
164 * @returns mixed returns the variant if it is valid, null otherwise
166 function validateVariant( $v = null ) {
167 if ( $v !== null && in_array( $v, $this->mVariants ) ) {
174 * Get the variant specified in the URL
176 * @returns mixed variant if one found, false otherwise.
178 function getURLVariant() {
182 if ( $this->mURLVariant ) {
183 return $this->mURLVariant;
186 // see if the preference is set in the request
187 $ret = $wgRequest->getText( 'variant' );
190 $ret = $wgRequest->getVal( 'uselang' );
193 return $this->mURLVariant = $this->validateVariant( $ret );
197 * Determine if the user has a variant set.
199 * @returns mixed variant if one found, false otherwise.
201 function getUserVariant() {
205 // memoizing this function wreaks havoc on parserTest.php
206 /* if ( $this->mUserVariant ) { */
207 /* return $this->mUserVariant; */
210 // get language variant preference from logged in users
211 // Don't call this on stub objects because that causes infinite
212 // recursion during initialisation
213 if ( $wgUser->isLoggedIn() ) {
214 $ret = $wgUser->getOption( 'variant' );
217 // figure out user lang without constructing wgLang to avoid
218 // infinite recursion
219 $ret = $wgUser->getOption( 'language' );
222 return $this->mUserVariant = $this->validateVariant( $ret );
227 * Determine the language variant from the Accept-Language header.
229 * @returns mixed variant if one found, false otherwise.
231 function getHeaderVariant() {
235 if ( $this->mHeaderVariant ) {
236 return $this->mHeaderVariant;
239 // see if some supported language variant is set in the
242 $acceptLanguage = $wgRequest->getHeader( 'Accept-Language' );
243 if ( !$acceptLanguage ) {
248 $result = StringUtils::explode( ',', strtolower( $acceptLanguage ) );
249 $languages = array();
251 foreach ( $result as $elem ) {
252 // if $elem likes 'zh-cn;q=0.9'
253 if ( ( $posi = strpos( $elem, ';' ) ) !== false ) {
254 // get the real language code likes 'zh-cn'
255 $languages[] = substr( $elem, 0, $posi );
257 $languages[] = $elem;
261 $fallback_languages = array();
262 foreach ( $languages as $language ) {
264 $language = trim( $language );
265 $this->mHeaderVariant = $this->validateVariant( $language );
266 if ( $this->mHeaderVariant ) {
270 // To see if there are fallbacks of current language.
271 // We record these fallback variants, and process
273 $fallbacks = $this->getVariantFallbacks( $language );
274 if ( is_string( $fallbacks ) ) {
275 $fallback_languages[] = $fallbacks;
276 } elseif ( is_array( $fallbacks ) ) {
277 $fallback_languages =
278 array_merge( $fallback_languages,
283 if ( !$this->mHeaderVariant ) {
284 // process fallback languages now
285 $fallback_languages = array_unique( $fallback_languages );
286 foreach ( $fallback_languages as $language ) {
287 $this->mHeaderVariant = $this->validateVariant( $language );
288 if ( $this->mHeaderVariant ) {
294 return $this->mHeaderVariant;
298 * Caption convert, base on preg_replace_callback.
300 * To convert text in "title" or "alt", like '<img alt="text" ... '
301 * or '<span title="text" ... '
303 * @return string like ' alt="yyyy"' or ' title="yyyy"'
306 function captionConvert( $matches ) {
307 $toVariant = $this->getPreferredVariant();
308 $title = $matches[1];
310 // we convert captions except URL
311 if ( !strpos( $text, '://' ) ) {
312 $text = $this->translate( $text, $toVariant );
314 return " $title=\"$text\"";
318 * Dictionary-based conversion.
320 * @param string $text the text to be converted
321 * @param string $toVariant the target language code
322 * @return string the converted text
325 function autoConvert( $text, $toVariant = false ) {
326 $fname = 'LanguageConverter::autoConvert';
328 wfProfileIn( $fname );
330 if ( !$this->mTablesLoaded ) {
335 $toVariant = $this->getPreferredVariant();
341 /* we convert everything except:
342 1. html markups (anything between < and >)
344 3. place holders created by the parser
347 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
348 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
353 // this one is needed when the text is inside an html markup
354 $htmlfix = '|<[^>]+$|^[^<>]*>';
356 // disable convert to variants between <code></code> tags
357 $codefix = '<code>.+?<\/code>|';
358 // disable convertsion of <script type="text/javascript"> ... </script>
359 $scriptfix = '<script.*?>.*?<\/script>|';
360 // disable conversion of <pre xxxx> ... </pre>
361 $prefix = '<pre.*?>.*?<\/pre>|';
363 $reg = '/' . $codefix . $scriptfix . $prefix .
364 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
366 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE );
368 $m = array_shift( $matches );
370 $ret = $this->translate( $m[0], $toVariant );
371 $mstart = $m[1] + strlen( $m[0] );
373 // enable convertsion of '<img alt="xxxx" ... '
374 // or '<span title="xxxx" ... '
375 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
380 foreach ( $matches as $m ) {
381 $mark = substr( $text, $mstart, $m[1] - $mstart );
382 $mark = preg_replace_callback( $captionpattern,
383 array( &$this, 'captionConvert' ),
385 // Let's convert the trtext only once,
386 // it would give us more performance improvement
388 $trtext .= $m[0] . $trtextmark;
389 $mstart = $m[1] + strlen( $m[0] );
392 $trtext = $this->translate( $trtext, $toVariant );
393 $trtext = StringUtils::explode( $trtextmark, $trtext );
394 foreach ( $trtext as $t ) {
395 $ret .= array_shift( $notrtext );
398 wfProfileOut( $fname );
403 * Translate a string to a variant.
404 * Doesn't process markup or do any of that other stuff, for that use
407 * @param string $text Text to convert
408 * @param string $variant Variant language code
409 * @return string Translated text
412 function translate( $text, $variant ) {
413 wfProfileIn( __METHOD__ );
414 // If $text is empty or only includes spaces, do nothing
415 // Otherwise translate it
416 if ( trim( $text ) ) {
417 if ( !$this->mTablesLoaded ) {
420 $text = $this->mTables[$variant]->replace( $text );
422 wfProfileOut( __METHOD__ );
427 * Convert text to all supported variants.
429 * @param string $text the text to be converted
430 * @return array of string
433 function autoConvertToAllVariants( $text ) {
434 $fname = 'LanguageConverter::autoConvertToAllVariants';
435 wfProfileIn( $fname );
436 if ( !$this->mTablesLoaded ) {
441 foreach ( $this->mVariants as $variant ) {
442 $ret[$variant] = $this->translate( $text, $variant );
445 wfProfileOut( $fname );
450 * Convert link text to all supported variants.
452 * @param string $text the text to be converted
453 * @return array of string
456 function convertLinkToAllVariants( $text ) {
457 if ( !$this->mTablesLoaded ) {
462 $tarray = StringUtils::explode( '-{', $text );
465 foreach ( $tarray as $txt ) {
468 foreach ( $this->mVariants as $variant ) {
469 $ret[$variant] = $this->translate( $txt, $variant );
474 $marked = explode( '}-', $txt, 2 );
476 foreach ( $this->mVariants as $variant ) {
477 $ret[$variant] .= '-{' . $marked[0] . '}-';
478 if ( array_key_exists( 1, $marked ) ) {
479 $ret[$variant] .= $this->translate( $marked[1], $variant );
489 * Prepare manual conversion table.
492 function applyManualConv( $convRule ) {
493 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
495 // Bug 24072: mConvRuleTitle won't work if the title conversion
496 // rule was followed by other manual conversion rule(s).
497 $newConvRuleTitle = $convRule->getTitle();
498 if( $newConvRuleTitle ) {
499 $this->mConvRuleTitle = $newConvRuleTitle;
502 // apply manual conversion table to global table
503 $convTable = $convRule->getConvTable();
504 $action = $convRule->getRulesAction();
505 foreach ( $convTable as $variant => $pair ) {
506 if ( !$this->validateVariant( $variant ) ) {
510 if ( $action == 'add' ) {
511 foreach ( $pair as $from => $to ) {
512 // to ensure that $from and $to not be left blank
513 // so $this->translate() could always return a string
514 if ( $from || $to ) {
515 // more efficient than array_merge(), about 2.5 times.
516 $this->mTables[$variant]->setPair( $from, $to );
519 } elseif ( $action == 'remove' ) {
520 $this->mTables[$variant]->removeArray( $pair );
526 * Convert text to different variants of a language. The automatic
527 * conversion is done in autoConvert(). Here we parse the text
528 * marked with -{}-, which specifies special conversions of the
529 * text that can not be accomplished in autoConvert().
531 * Syntax of the markup:
532 * -{code1:text1;code2:text2;...}- or
533 * -{flags|code1:text1;code2:text2;...}- or
534 * -{text}- in which case no conversion should take place for text
536 * @param $text String: text to be converted
537 * @return String: converted text
539 public function convert( $text ) {
540 global $wgDisableLangConversion;
541 if ( $wgDisableLangConversion ) return $text;
543 $variant = $this->getPreferredVariant();
545 return $this->recursiveConvertTopLevel( $text, $variant );
549 * Convert a Title object to a readable string in the preferred variant
551 public function convertTitle( $title ) {
552 $variant = $this->getPreferredVariant();
553 $index = $title->getNamespace();
554 if ( $index === NS_MAIN ) {
557 // first let's check if a message has given us a converted name
558 $nsConvKey = 'conversion-ns' . $index;
559 if ( !wfEmptyMsg( $nsConvKey ) ) {
560 $text = wfMsgForContentNoTrans( $nsConvKey );
562 // the message does not exist, try retrieve it from the current
563 // variant's namespace names.
564 $langObj = $this->mLangObj->factory( $variant );
565 $text = $langObj->getFormattedNsText( $index );
569 $text .= $title->getText();
570 $text = $this->autoConvert( $text, $variant );
574 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
577 $length = strlen( $text );
578 while ( $startPos < $length ) {
580 $pos = strpos( $text, '-{', $startPos );
582 if ( $pos === false ) {
583 // No more markup, append final segment
584 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
590 // Append initial segment
591 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
596 // Do recursive conversion
597 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
603 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
604 // Quick sanity check (no function calls)
605 if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
606 throw new MWException( __METHOD__.': invalid input string' );
611 $warningDone = false;
612 $length = strlen( $text );
614 while ( $startPos < $length ) {
616 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
626 // Append initial segment
627 $inner .= substr( $text, $startPos, $pos - $startPos );
635 if ( $depth >= $this->mMaxDepth ) {
637 if ( !$warningDone ) {
638 $inner .= '<span class="error">' .
639 wfMsgForContent( 'language-converter-depth-warning',
647 // Recursively parse another rule
648 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
653 $rule = new ConverterRule( $inner, $this );
654 $rule->parse( $variant );
655 $this->applyManualConv( $rule );
656 return $rule->getDisplay();
658 throw new MWException( __METHOD__.': invalid regex match' );
663 if ( $startPos < $length ) {
664 $inner .= substr( $text, $startPos );
667 return '-{' . $this->autoConvert( $inner, $variant );
671 * If a language supports multiple variants, it is
672 * possible that non-existing link in one variant
673 * actually exists in another variant. This function
674 * tries to find it. See e.g. LanguageZh.php
676 * @param string $link the name of the link
677 * @param mixed $nt the title object of the link
678 * @param boolean $ignoreOtherCond: to disable other conditions when
679 * we need to transclude a template or update a category's link
680 * @return null the input parameters may be modified upon return
683 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
684 # If the article has already existed, there is no need to
685 # check it again, otherwise it may cause a fault.
686 if ( is_object( $nt ) && $nt->exists() ) {
690 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
692 $isredir = $wgRequest->getText( 'redirect', 'yes' );
693 $action = $wgRequest->getText( 'action' );
694 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
695 $disableLinkConversion = $wgDisableLangConversion
696 || $wgDisableTitleConversion;
697 $linkBatch = new LinkBatch();
701 if ( $disableLinkConversion ||
702 ( !$ignoreOtherCond &&
705 || $action == 'submit'
706 || $linkconvert == 'no'
707 || $wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
711 if ( is_object( $nt ) ) {
712 $ns = $nt->getNamespace();
715 $variants = $this->autoConvertToAllVariants( $link );
716 if ( $variants == false ) { // give up
722 foreach ( $variants as $v ) {
724 $varnt = Title::newFromText( $v, $ns );
725 if ( !is_null( $varnt ) ) {
726 $linkBatch->addObj( $varnt );
732 // fetch all variants in single query
733 $linkBatch->execute();
735 foreach ( $titles as $varnt ) {
736 if ( $varnt->getArticleID() > 0 ) {
738 $link = $varnt->getText();
745 * Returns language specific hash options.
749 function getExtraHashOptions() {
750 $variant = $this->getPreferredVariant();
751 return '!' . $variant ;
755 * Load default conversion tables.
756 * This method must be implemented in derived class.
760 function loadDefaultTables() {
761 $name = get_class( $this );
762 wfDie( "Must implement loadDefaultTables() method in class $name" );
766 * Load conversion tables either from the cache or the disk.
769 function loadTables( $fromcache = true ) {
771 if ( $this->mTablesLoaded ) {
774 wfProfileIn( __METHOD__ );
775 $this->mTablesLoaded = true;
776 $this->mTables = false;
778 wfProfileIn( __METHOD__ . '-cache' );
779 $this->mTables = $wgMemc->get( $this->mCacheKey );
780 wfProfileOut( __METHOD__ . '-cache' );
783 || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
784 wfProfileIn( __METHOD__ . '-recache' );
785 // not in cache, or we need a fresh reload.
786 // we will first load the default tables
787 // then update them using things in MediaWiki:Zhconversiontable/*
788 $this->loadDefaultTables();
789 foreach ( $this->mVariants as $var ) {
790 $cached = $this->parseCachedTable( $var );
791 $this->mTables[$var]->mergeArray( $cached );
794 $this->postLoadTables();
795 $this->mTables[self::CACHE_VERSION_KEY] = true;
797 $wgMemc->set( $this->mCacheKey, $this->mTables, 43200 );
798 wfProfileOut( __METHOD__ . '-recache' );
800 wfProfileOut( __METHOD__ );
804 * Hook for post processig after conversion tables are loaded.
807 function postLoadTables() { }
810 * Reload the conversion tables.
814 function reloadTables() {
815 if ( $this->mTables ) {
816 unset( $this->mTables );
818 $this->mTablesLoaded = false;
819 $this->loadTables( false );
824 * Parse the conversion table stored in the cache.
826 * The tables should be in blocks of the following form:
833 * To make the tables more manageable, subpages are allowed
834 * and will be parsed recursively if $recursive == true.
837 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
838 global $wgMessageCache;
839 static $parsed = array();
841 if ( !is_object( $wgMessageCache ) ) {
845 $key = 'Conversiontable/' . $code;
847 $key .= '/' . $subpage;
849 if ( array_key_exists( $key, $parsed ) ) {
853 if ( strpos( $code, '/' ) === false ) {
854 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
856 $title = Title::makeTitleSafe( NS_MEDIAWIKI,
857 "Conversiontable/$code" );
858 if ( $title && $title->exists() ) {
859 $article = new Article( $title );
860 $txt = $article->getContents();
866 // get all subpage links of the form
867 // [[MediaWiki:conversiontable/zh-xx/...|...]]
868 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
870 $subs = StringUtils::explode( '[[', $txt );
872 foreach ( $subs as $sub ) {
873 $link = explode( ']]', $sub, 2 );
874 if ( count( $link ) != 2 ) {
877 $b = explode( '|', $link[0], 2 );
878 $b = explode( '/', trim( $b[0] ), 3 );
879 if ( count( $b ) == 3 ) {
885 if ( $b[0] == $linkhead && $b[1] == $code ) {
886 $sublinks[] = $sublink;
891 // parse the mappings in this page
892 $blocks = StringUtils::explode( '-{', $txt );
895 foreach ( $blocks as $block ) {
897 // Skip the part before the first -{
901 $mappings = explode( '}-', $block, 2 );
902 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
904 $table = StringUtils::explode( ';', $stripped );
905 foreach ( $table as $t ) {
906 $m = explode( '=>', $t, 3 );
907 if ( count( $m ) != 2 )
909 // trim any trailling comments starting with '//'
910 $tt = explode( '//', $m[1], 2 );
911 $ret[trim( $m[0] )] = trim( $tt[0] );
914 $parsed[$key] = true;
917 // recursively parse the subpages
919 foreach ( $sublinks as $link ) {
920 $s = $this->parseCachedTable( $code, $link, $recursive );
921 $ret = array_merge( $ret, $s );
925 if ( $this->mUcfirst ) {
926 foreach ( $ret as $k => $v ) {
927 $ret[Language::ucfirst( $k )] = Language::ucfirst( $v );
934 * Enclose a string with the "no conversion" tag. This is used by
935 * various functions in the Parser.
937 * @param string $text text to be tagged for no conversion
938 * @return string the tagged text
941 function markNoConversion( $text, $noParse = false ) {
942 # don't mark if already marked
943 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
947 $ret = "-{R|$text}-";
952 * Convert the sorting key for category links. This should make different
953 * keys that are variants of each other map to the same key.
955 function convertCategoryKey( $key ) {
960 * Hook to refresh the cache of conversion tables when
961 * MediaWiki:conversiontable* is updated.
964 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
965 $iswatch, $section, $flags, $revision ) {
966 $titleobj = $article->getTitle();
967 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
968 $title = $titleobj->getDBkey();
969 $t = explode( '/', $title, 3 );
971 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
972 if ( $this->validateVariant( $t[1] ) ) {
973 $this->reloadTables();
981 * Armour rendered math against conversion.
982 * Wrap math into rawoutput -{R| math }- syntax.
985 function armourMath( $text ) {
986 // we need to convert '-{' and '}-' to '-{' and '}-'
987 // to avoid a unwanted '}-' appeared after the math-image.
988 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
989 $ret = "-{R|$text}-";
994 * Get the cached separator pattern for ConverterRule::parseRules()
996 function getVarSeparatorPattern() {
997 if ( is_null( $this->mVarSeparatorPattern ) ) {
998 // varsep_pattern for preg_split:
999 // text should be splited by ";" only if a valid variant
1000 // name exist after the markup, for example:
1001 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1002 // <span style="font-size:120%;">yyy</span>;}-
1003 // we should split it as:
1005 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1006 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1010 foreach ( $this->mVariants as $variant ) {
1011 // zh-hans:xxx;zh-hant:yyy
1012 $pat .= $variant . '\s*:|';
1013 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1014 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1017 $this->mVarSeparatorPattern = $pat;
1019 return $this->mVarSeparatorPattern;
1024 * Parser for rules of language conversion , parse rules in -{ }- tag.
1026 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1028 class ConverterRule {
1029 var $mText; // original text in -{text}-
1030 var $mConverter; // LanguageConverter object
1031 var $mManualCodeError = '<strong class="error">code error!</strong>';
1032 var $mRuleDisplay = '';
1033 var $mRuleTitle = false;
1034 var $mRules = '';// string : the text of the rules
1035 var $mRulesAction = 'none';
1036 var $mFlags = array();
1037 var $mVariantFlags = array();
1038 var $mConvTable = array();
1039 var $mBidtable = array();// array of the translation in each variant
1040 var $mUnidtable = array();// array of the translation in each variant
1045 * @param $text String: the text between -{ and }-
1046 * @param $converter LanguageConverter object
1048 public function __construct( $text, $converter ) {
1049 $this->mText = $text;
1050 $this->mConverter = $converter;
1054 * Check if variants array in convert array.
1056 * @param $variants Array or string: variant language code
1057 * @return String: translated text
1059 public function getTextInBidtable( $variants ) {
1060 $variants = (array)$variants;
1064 foreach ( $variants as $variant ) {
1065 if ( isset( $this->mBidtable[$variant] ) ) {
1066 return $this->mBidtable[$variant];
1073 * Parse flags with syntax -{FLAG| ... }-
1076 function parseFlags() {
1077 $text = $this->mText;
1079 $variantFlags = array();
1081 $sepPos = strpos( $text, '|' );
1082 if ( $sepPos !== false ) {
1083 $validFlags = $this->mConverter->mFlags;
1084 $f = StringUtils::explode( ';', substr( $text, 0, $sepPos ) );
1085 foreach ( $f as $ff ) {
1087 if ( isset( $validFlags[$ff] ) ) {
1088 $flags[$validFlags[$ff]] = true;
1091 $text = strval( substr( $text, $sepPos + 1 ) );
1096 } elseif ( isset( $flags['R'] ) ) {
1097 $flags = array( 'R' => true );// remove other flags
1098 } elseif ( isset( $flags['N'] ) ) {
1099 $flags = array( 'N' => true );// remove other flags
1100 } elseif ( isset( $flags['-'] ) ) {
1101 $flags = array( '-' => true );// remove other flags
1102 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1104 } elseif ( isset( $flags['H'] ) ) {
1105 // replace A flag, and remove other flags except T
1106 $temp = array( '+' => true, 'H' => true );
1107 if ( isset( $flags['T'] ) ) {
1110 if ( isset( $flags['D'] ) ) {
1115 if ( isset( $flags['A'] ) ) {
1119 if ( isset( $flags['D'] ) ) {
1120 unset( $flags['S'] );
1122 // try to find flags like "zh-hans", "zh-hant"
1123 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1124 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter->mVariants );
1125 if ( $variantFlags ) {
1126 $variantFlags = array_flip( $variantFlags );
1130 $this->mVariantFlags = $variantFlags;
1131 $this->mRules = $text;
1132 $this->mFlags = $flags;
1136 * Generate conversion table.
1139 function parseRules() {
1140 $rules = $this->mRules;
1141 $flags = $this->mFlags;
1142 $bidtable = array();
1143 $unidtable = array();
1144 $variants = $this->mConverter->mVariants;
1145 $varsep_pattern = $this->mConverter->getVarSeparatorPattern();
1147 $choice = preg_split( $varsep_pattern, $rules );
1149 foreach ( $choice as $c ) {
1150 $v = explode( ':', $c, 2 );
1151 if ( count( $v ) != 2 ) {
1152 // syntax error, skip
1155 $to = trim( $v[1] );
1157 $u = explode( '=>', $v, 2 );
1158 // if $to is empty, strtr() could return a wrong result
1159 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1160 $bidtable[$v] = $to;
1161 } elseif ( count( $u ) == 2 ) {
1162 $from = trim( $u[0] );
1164 if ( array_key_exists( $v, $unidtable )
1165 && !is_array( $unidtable[$v] )
1167 && in_array( $v, $variants ) ) {
1168 $unidtable[$v] = array( $from => $to );
1169 } elseif ( $to && in_array( $v, $variants ) ) {
1170 $unidtable[$v][$from] = $to;
1173 // syntax error, pass
1174 if ( !isset( $this->mConverter->mVariantNames[$v] ) ) {
1175 $bidtable = array();
1176 $unidtable = array();
1180 $this->mBidtable = $bidtable;
1181 $this->mUnidtable = $unidtable;
1187 function getRulesDesc() {
1188 $codesep = $this->mConverter->mDescCodeSep;
1189 $varsep = $this->mConverter->mDescVarSep;
1191 foreach ( $this->mBidtable as $k => $v ) {
1192 $text .= $this->mConverter->mVariantNames[$k] . "$codesep$v$varsep";
1194 foreach ( $this->mUnidtable as $k => $a ) {
1195 foreach ( $a as $from => $to ) {
1196 $text .= $from . '⇒' . $this->mConverter->mVariantNames[$k] .
1197 "$codesep$to$varsep";
1204 * Parse rules conversion.
1207 function getRuleConvertedStr( $variant ) {
1208 $bidtable = $this->mBidtable;
1209 $unidtable = $this->mUnidtable;
1211 if ( count( $bidtable ) + count( $unidtable ) == 0 ) {
1212 return $this->mRules;
1214 // display current variant in bidirectional array
1215 $disp = $this->getTextInBidtable( $variant );
1216 // or display current variant in fallbacks
1218 $disp = $this->getTextInBidtable(
1219 $this->mConverter->getVariantFallbacks( $variant ) );
1221 // or display current variant in unidirectional array
1222 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1223 $disp = array_values( $unidtable[$variant] );
1226 // or display frist text under disable manual convert
1228 && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
1229 if ( count( $bidtable ) > 0 ) {
1230 $disp = array_values( $bidtable );
1233 $disp = array_values( $unidtable );
1234 $disp = array_values( $disp[0] );
1243 * Generate conversion table for all text.
1246 function generateConvTable() {
1247 // Special case optimisation
1248 if ( !$this->mBidtable && !$this->mUnidtable ) {
1249 $this->mConvTable = array();
1253 $bidtable = $this->mBidtable;
1254 $unidtable = $this->mUnidtable;
1255 $manLevel = $this->mConverter->mManualLevel;
1258 foreach ( $this->mConverter->mVariants as $v ) {
1259 /* for bidirectional array
1260 fill in the missing variants, if any,
1262 if ( !isset( $bidtable[$v] ) ) {
1264 $this->mConverter->getVariantFallbacks( $v );
1265 $vf = $this->getTextInBidtable( $variantFallbacks );
1267 $bidtable[$v] = $vf;
1271 if ( isset( $bidtable[$v] ) ) {
1272 foreach ( $vmarked as $vo ) {
1273 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1274 // or -{H|zh:WordZh;zh-tw:WordTw}-
1275 // or -{-|zh:WordZh;zh-tw:WordTw}-
1276 // to introduce a custom mapping between
1277 // words WordZh and WordTw in the whole text
1278 if ( $manLevel[$v] == 'bidirectional' ) {
1279 $this->mConvTable[$v][$bidtable[$vo]] = $bidtable[$v];
1281 if ( $manLevel[$vo] == 'bidirectional' ) {
1282 $this->mConvTable[$vo][$bidtable[$v]] = $bidtable[$vo];
1287 /*for unidirectional array fill to convert tables */
1288 if ( ( $manLevel[$v] == 'bidirectional' || $manLevel[$v] == 'unidirectional' )
1289 && isset( $unidtable[$v] ) )
1291 if ( isset( $this->mConvTable[$v] ) ) {
1292 $this->mConvTable[$v] = array_merge( $this->mConvTable[$v], $unidtable[$v] );
1294 $this->mConvTable[$v] = $unidtable[$v];
1301 * Parse rules and flags.
1304 function parse( $variant = NULL ) {
1306 $variant = $this->mConverter->getPreferredVariant();
1309 $variants = $this->mConverter->mVariants;
1310 $this->parseFlags();
1311 $flags = $this->mFlags;
1313 // convert to specified variant
1314 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1315 if ( $this->mVariantFlags ) {
1316 // check if current variant in flags
1317 if ( isset( $this->mVariantFlags[$variant] ) ) {
1318 // then convert <text to convert> to current language
1319 $this->mRules = $this->mConverter->autoConvert( $this->mRules,
1321 } else { // if current variant no in flags,
1322 // then we check its fallback variants.
1324 $this->mConverter->getVariantFallbacks( $variant );
1325 foreach ( $variantFallbacks as $variantFallback ) {
1326 // if current variant's fallback exist in flags
1327 if ( isset( $this->mVariantFlags[$variantFallback] ) ) {
1328 // then convert <text to convert> to fallback language
1330 $this->mConverter->autoConvert( $this->mRules,
1336 $this->mFlags = $flags = array( 'R' => true );
1339 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1340 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1341 $this->mRules = str_replace( '=>', '=>', $this->mRules );
1342 $this->parseRules();
1344 $rules = $this->mRules;
1346 if ( !$this->mBidtable && !$this->mUnidtable ) {
1347 if ( isset( $flags['+'] ) || isset( $flags['-'] ) ) {
1348 // fill all variants if text in -{A/H/-|text} without rules
1349 foreach ( $this->mConverter->mVariants as $v ) {
1350 $this->mBidtable[$v] = $rules;
1352 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1353 $this->mFlags = $flags = array( 'R' => true );
1357 $this->mRuleDisplay = false;
1358 foreach ( $flags as $flag => $unused ) {
1361 // if we don't do content convert, still strip the -{}- tags
1362 $this->mRuleDisplay = $rules;
1365 // process N flag: output current variant name
1366 $ruleVar = trim( $rules );
1367 if ( isset( $this->mConverter->mVariantNames[$ruleVar] ) ) {
1368 $this->mRuleDisplay = $this->mConverter->mVariantNames[$ruleVar];
1370 $this->mRuleDisplay = '';
1374 // process D flag: output rules description
1375 $this->mRuleDisplay = $this->getRulesDesc();
1378 // process H,- flag or T only: output nothing
1379 $this->mRuleDisplay = '';
1382 $this->mRulesAction = 'remove';
1383 $this->mRuleDisplay = '';
1386 $this->mRulesAction = 'add';
1387 $this->mRuleDisplay = '';
1390 $this->mRuleDisplay = $this->getRuleConvertedStr( $variant );
1393 $this->mRuleTitle = $this->getRuleConvertedStr( $variant );
1394 $this->mRuleDisplay = '';
1397 // ignore unknown flags (but see error case below)
1400 if ( $this->mRuleDisplay === false ) {
1401 $this->mRuleDisplay = $this->mManualCodeError;
1404 $this->generateConvTable();
1410 function hasRules() {
1415 * Get display text on markup -{...}-
1418 function getDisplay() {
1419 return $this->mRuleDisplay;
1423 * Get converted title.
1426 function getTitle() {
1427 return $this->mRuleTitle;
1431 * Return how deal with conversion rules.
1434 function getRulesAction() {
1435 return $this->mRulesAction;
1439 * Get conversion table. ( bidirectional and unidirectional
1440 * conversion table )
1443 function getConvTable() {
1444 return $this->mConvTable;
1448 * Get conversion rules string.
1451 function getRules() {
1452 return $this->mRules;
1456 * Get conversion flags.
1459 function getFlags() {
1460 return $this->mFlags;