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 || $index === NS_SPECIAL ) {
557 // first let's check if a message has given us a converted name
558 $nsConvKey = 'conversion-ns' . $index;
559 $nsLocalText = wfMsgForContentNoTrans( $nsConvKey );
560 if ( !wfEmptyMsg( $nsConvKey, $nsLocalText ) ) {
561 $text = $nsLocalText;
563 // the message does not exist, try retrieve it from the current
564 // variant's namespace names.
565 $langObj = $this->mLangObj->factory( $variant );
566 $text = $langObj->getFormattedNsText( $index );
570 $text .= $title->getText();
571 $text = $this->autoConvert( $text, $variant );
575 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
578 $length = strlen( $text );
579 while ( $startPos < $length ) {
581 $pos = strpos( $text, '-{', $startPos );
583 if ( $pos === false ) {
584 // No more markup, append final segment
585 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
591 // Append initial segment
592 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
597 // Do recursive conversion
598 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
604 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
605 // Quick sanity check (no function calls)
606 if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
607 throw new MWException( __METHOD__.': invalid input string' );
612 $warningDone = false;
613 $length = strlen( $text );
615 while ( $startPos < $length ) {
617 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
627 // Append initial segment
628 $inner .= substr( $text, $startPos, $pos - $startPos );
636 if ( $depth >= $this->mMaxDepth ) {
638 if ( !$warningDone ) {
639 $inner .= '<span class="error">' .
640 wfMsgForContent( 'language-converter-depth-warning',
648 // Recursively parse another rule
649 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
654 $rule = new ConverterRule( $inner, $this );
655 $rule->parse( $variant );
656 $this->applyManualConv( $rule );
657 return $rule->getDisplay();
659 throw new MWException( __METHOD__.': invalid regex match' );
664 if ( $startPos < $length ) {
665 $inner .= substr( $text, $startPos );
668 return '-{' . $this->autoConvert( $inner, $variant );
672 * If a language supports multiple variants, it is
673 * possible that non-existing link in one variant
674 * actually exists in another variant. This function
675 * tries to find it. See e.g. LanguageZh.php
677 * @param string $link the name of the link
678 * @param mixed $nt the title object of the link
679 * @param boolean $ignoreOtherCond: to disable other conditions when
680 * we need to transclude a template or update a category's link
681 * @return null the input parameters may be modified upon return
684 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
685 # If the article has already existed, there is no need to
686 # check it again, otherwise it may cause a fault.
687 if ( is_object( $nt ) && $nt->exists() ) {
691 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
693 $isredir = $wgRequest->getText( 'redirect', 'yes' );
694 $action = $wgRequest->getText( 'action' );
695 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
696 $disableLinkConversion = $wgDisableLangConversion
697 || $wgDisableTitleConversion;
698 $linkBatch = new LinkBatch();
702 if ( $disableLinkConversion ||
703 ( !$ignoreOtherCond &&
706 || $action == 'submit'
707 || $linkconvert == 'no'
708 || $wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
712 if ( is_object( $nt ) ) {
713 $ns = $nt->getNamespace();
716 $variants = $this->autoConvertToAllVariants( $link );
717 if ( $variants == false ) { // give up
723 foreach ( $variants as $v ) {
725 $varnt = Title::newFromText( $v, $ns );
726 if ( !is_null( $varnt ) ) {
727 $linkBatch->addObj( $varnt );
733 // fetch all variants in single query
734 $linkBatch->execute();
736 foreach ( $titles as $varnt ) {
737 if ( $varnt->getArticleID() > 0 ) {
739 $link = $varnt->getText();
746 * Returns language specific hash options.
750 function getExtraHashOptions() {
751 $variant = $this->getPreferredVariant();
752 return '!' . $variant ;
756 * Load default conversion tables.
757 * This method must be implemented in derived class.
761 function loadDefaultTables() {
762 $name = get_class( $this );
763 wfDie( "Must implement loadDefaultTables() method in class $name" );
767 * Load conversion tables either from the cache or the disk.
770 function loadTables( $fromcache = true ) {
772 if ( $this->mTablesLoaded ) {
775 wfProfileIn( __METHOD__ );
776 $this->mTablesLoaded = true;
777 $this->mTables = false;
779 wfProfileIn( __METHOD__ . '-cache' );
780 $this->mTables = $wgMemc->get( $this->mCacheKey );
781 wfProfileOut( __METHOD__ . '-cache' );
784 || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
785 wfProfileIn( __METHOD__ . '-recache' );
786 // not in cache, or we need a fresh reload.
787 // we will first load the default tables
788 // then update them using things in MediaWiki:Zhconversiontable/*
789 $this->loadDefaultTables();
790 foreach ( $this->mVariants as $var ) {
791 $cached = $this->parseCachedTable( $var );
792 $this->mTables[$var]->mergeArray( $cached );
795 $this->postLoadTables();
796 $this->mTables[self::CACHE_VERSION_KEY] = true;
798 $wgMemc->set( $this->mCacheKey, $this->mTables, 43200 );
799 wfProfileOut( __METHOD__ . '-recache' );
801 wfProfileOut( __METHOD__ );
805 * Hook for post processig after conversion tables are loaded.
808 function postLoadTables() { }
811 * Reload the conversion tables.
815 function reloadTables() {
816 if ( $this->mTables ) {
817 unset( $this->mTables );
819 $this->mTablesLoaded = false;
820 $this->loadTables( false );
825 * Parse the conversion table stored in the cache.
827 * The tables should be in blocks of the following form:
834 * To make the tables more manageable, subpages are allowed
835 * and will be parsed recursively if $recursive == true.
838 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
839 global $wgMessageCache;
840 static $parsed = array();
842 if ( !is_object( $wgMessageCache ) ) {
846 $key = 'Conversiontable/' . $code;
848 $key .= '/' . $subpage;
850 if ( array_key_exists( $key, $parsed ) ) {
854 if ( strpos( $code, '/' ) === false ) {
855 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
857 $title = Title::makeTitleSafe( NS_MEDIAWIKI,
858 "Conversiontable/$code" );
859 if ( $title && $title->exists() ) {
860 $article = new Article( $title );
861 $txt = $article->getContents();
867 // get all subpage links of the form
868 // [[MediaWiki:conversiontable/zh-xx/...|...]]
869 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
871 $subs = StringUtils::explode( '[[', $txt );
873 foreach ( $subs as $sub ) {
874 $link = explode( ']]', $sub, 2 );
875 if ( count( $link ) != 2 ) {
878 $b = explode( '|', $link[0], 2 );
879 $b = explode( '/', trim( $b[0] ), 3 );
880 if ( count( $b ) == 3 ) {
886 if ( $b[0] == $linkhead && $b[1] == $code ) {
887 $sublinks[] = $sublink;
892 // parse the mappings in this page
893 $blocks = StringUtils::explode( '-{', $txt );
896 foreach ( $blocks as $block ) {
898 // Skip the part before the first -{
902 $mappings = explode( '}-', $block, 2 );
903 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
905 $table = StringUtils::explode( ';', $stripped );
906 foreach ( $table as $t ) {
907 $m = explode( '=>', $t, 3 );
908 if ( count( $m ) != 2 )
910 // trim any trailling comments starting with '//'
911 $tt = explode( '//', $m[1], 2 );
912 $ret[trim( $m[0] )] = trim( $tt[0] );
915 $parsed[$key] = true;
918 // recursively parse the subpages
920 foreach ( $sublinks as $link ) {
921 $s = $this->parseCachedTable( $code, $link, $recursive );
922 $ret = array_merge( $ret, $s );
926 if ( $this->mUcfirst ) {
927 foreach ( $ret as $k => $v ) {
928 $ret[Language::ucfirst( $k )] = Language::ucfirst( $v );
935 * Enclose a string with the "no conversion" tag. This is used by
936 * various functions in the Parser.
938 * @param string $text text to be tagged for no conversion
939 * @return string the tagged text
942 function markNoConversion( $text, $noParse = false ) {
943 # don't mark if already marked
944 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
948 $ret = "-{R|$text}-";
953 * Convert the sorting key for category links. This should make different
954 * keys that are variants of each other map to the same key.
956 function convertCategoryKey( $key ) {
961 * Hook to refresh the cache of conversion tables when
962 * MediaWiki:conversiontable* is updated.
965 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
966 $iswatch, $section, $flags, $revision ) {
967 $titleobj = $article->getTitle();
968 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
969 $title = $titleobj->getDBkey();
970 $t = explode( '/', $title, 3 );
972 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
973 if ( $this->validateVariant( $t[1] ) ) {
974 $this->reloadTables();
982 * Armour rendered math against conversion.
983 * Wrap math into rawoutput -{R| math }- syntax.
986 function armourMath( $text ) {
987 // we need to convert '-{' and '}-' to '-{' and '}-'
988 // to avoid a unwanted '}-' appeared after the math-image.
989 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
990 $ret = "-{R|$text}-";
995 * Get the cached separator pattern for ConverterRule::parseRules()
997 function getVarSeparatorPattern() {
998 if ( is_null( $this->mVarSeparatorPattern ) ) {
999 // varsep_pattern for preg_split:
1000 // text should be splited by ";" only if a valid variant
1001 // name exist after the markup, for example:
1002 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1003 // <span style="font-size:120%;">yyy</span>;}-
1004 // we should split it as:
1006 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1007 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1011 foreach ( $this->mVariants as $variant ) {
1012 // zh-hans:xxx;zh-hant:yyy
1013 $pat .= $variant . '\s*:|';
1014 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1015 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1018 $this->mVarSeparatorPattern = $pat;
1020 return $this->mVarSeparatorPattern;
1025 * Parser for rules of language conversion , parse rules in -{ }- tag.
1027 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1029 class ConverterRule {
1030 var $mText; // original text in -{text}-
1031 var $mConverter; // LanguageConverter object
1032 var $mManualCodeError = '<strong class="error">code error!</strong>';
1033 var $mRuleDisplay = '';
1034 var $mRuleTitle = false;
1035 var $mRules = '';// string : the text of the rules
1036 var $mRulesAction = 'none';
1037 var $mFlags = array();
1038 var $mVariantFlags = array();
1039 var $mConvTable = array();
1040 var $mBidtable = array();// array of the translation in each variant
1041 var $mUnidtable = array();// array of the translation in each variant
1046 * @param $text String: the text between -{ and }-
1047 * @param $converter LanguageConverter object
1049 public function __construct( $text, $converter ) {
1050 $this->mText = $text;
1051 $this->mConverter = $converter;
1055 * Check if variants array in convert array.
1057 * @param $variants Array or string: variant language code
1058 * @return String: translated text
1060 public function getTextInBidtable( $variants ) {
1061 $variants = (array)$variants;
1065 foreach ( $variants as $variant ) {
1066 if ( isset( $this->mBidtable[$variant] ) ) {
1067 return $this->mBidtable[$variant];
1074 * Parse flags with syntax -{FLAG| ... }-
1077 function parseFlags() {
1078 $text = $this->mText;
1080 $variantFlags = array();
1082 $sepPos = strpos( $text, '|' );
1083 if ( $sepPos !== false ) {
1084 $validFlags = $this->mConverter->mFlags;
1085 $f = StringUtils::explode( ';', substr( $text, 0, $sepPos ) );
1086 foreach ( $f as $ff ) {
1088 if ( isset( $validFlags[$ff] ) ) {
1089 $flags[$validFlags[$ff]] = true;
1092 $text = strval( substr( $text, $sepPos + 1 ) );
1097 } elseif ( isset( $flags['R'] ) ) {
1098 $flags = array( 'R' => true );// remove other flags
1099 } elseif ( isset( $flags['N'] ) ) {
1100 $flags = array( 'N' => true );// remove other flags
1101 } elseif ( isset( $flags['-'] ) ) {
1102 $flags = array( '-' => true );// remove other flags
1103 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1105 } elseif ( isset( $flags['H'] ) ) {
1106 // replace A flag, and remove other flags except T
1107 $temp = array( '+' => true, 'H' => true );
1108 if ( isset( $flags['T'] ) ) {
1111 if ( isset( $flags['D'] ) ) {
1116 if ( isset( $flags['A'] ) ) {
1120 if ( isset( $flags['D'] ) ) {
1121 unset( $flags['S'] );
1123 // try to find flags like "zh-hans", "zh-hant"
1124 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1125 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter->mVariants );
1126 if ( $variantFlags ) {
1127 $variantFlags = array_flip( $variantFlags );
1131 $this->mVariantFlags = $variantFlags;
1132 $this->mRules = $text;
1133 $this->mFlags = $flags;
1137 * Generate conversion table.
1140 function parseRules() {
1141 $rules = $this->mRules;
1142 $flags = $this->mFlags;
1143 $bidtable = array();
1144 $unidtable = array();
1145 $variants = $this->mConverter->mVariants;
1146 $varsep_pattern = $this->mConverter->getVarSeparatorPattern();
1148 $choice = preg_split( $varsep_pattern, $rules );
1150 foreach ( $choice as $c ) {
1151 $v = explode( ':', $c, 2 );
1152 if ( count( $v ) != 2 ) {
1153 // syntax error, skip
1156 $to = trim( $v[1] );
1158 $u = explode( '=>', $v, 2 );
1159 // if $to is empty, strtr() could return a wrong result
1160 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1161 $bidtable[$v] = $to;
1162 } elseif ( count( $u ) == 2 ) {
1163 $from = trim( $u[0] );
1165 if ( array_key_exists( $v, $unidtable )
1166 && !is_array( $unidtable[$v] )
1168 && in_array( $v, $variants ) ) {
1169 $unidtable[$v] = array( $from => $to );
1170 } elseif ( $to && in_array( $v, $variants ) ) {
1171 $unidtable[$v][$from] = $to;
1174 // syntax error, pass
1175 if ( !isset( $this->mConverter->mVariantNames[$v] ) ) {
1176 $bidtable = array();
1177 $unidtable = array();
1181 $this->mBidtable = $bidtable;
1182 $this->mUnidtable = $unidtable;
1188 function getRulesDesc() {
1189 $codesep = $this->mConverter->mDescCodeSep;
1190 $varsep = $this->mConverter->mDescVarSep;
1192 foreach ( $this->mBidtable as $k => $v ) {
1193 $text .= $this->mConverter->mVariantNames[$k] . "$codesep$v$varsep";
1195 foreach ( $this->mUnidtable as $k => $a ) {
1196 foreach ( $a as $from => $to ) {
1197 $text .= $from . '⇒' . $this->mConverter->mVariantNames[$k] .
1198 "$codesep$to$varsep";
1205 * Parse rules conversion.
1208 function getRuleConvertedStr( $variant ) {
1209 $bidtable = $this->mBidtable;
1210 $unidtable = $this->mUnidtable;
1212 if ( count( $bidtable ) + count( $unidtable ) == 0 ) {
1213 return $this->mRules;
1215 // display current variant in bidirectional array
1216 $disp = $this->getTextInBidtable( $variant );
1217 // or display current variant in fallbacks
1219 $disp = $this->getTextInBidtable(
1220 $this->mConverter->getVariantFallbacks( $variant ) );
1222 // or display current variant in unidirectional array
1223 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1224 $disp = array_values( $unidtable[$variant] );
1227 // or display frist text under disable manual convert
1229 && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
1230 if ( count( $bidtable ) > 0 ) {
1231 $disp = array_values( $bidtable );
1234 $disp = array_values( $unidtable );
1235 $disp = array_values( $disp[0] );
1244 * Generate conversion table for all text.
1247 function generateConvTable() {
1248 // Special case optimisation
1249 if ( !$this->mBidtable && !$this->mUnidtable ) {
1250 $this->mConvTable = array();
1254 $bidtable = $this->mBidtable;
1255 $unidtable = $this->mUnidtable;
1256 $manLevel = $this->mConverter->mManualLevel;
1259 foreach ( $this->mConverter->mVariants as $v ) {
1260 /* for bidirectional array
1261 fill in the missing variants, if any,
1263 if ( !isset( $bidtable[$v] ) ) {
1265 $this->mConverter->getVariantFallbacks( $v );
1266 $vf = $this->getTextInBidtable( $variantFallbacks );
1268 $bidtable[$v] = $vf;
1272 if ( isset( $bidtable[$v] ) ) {
1273 foreach ( $vmarked as $vo ) {
1274 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1275 // or -{H|zh:WordZh;zh-tw:WordTw}-
1276 // or -{-|zh:WordZh;zh-tw:WordTw}-
1277 // to introduce a custom mapping between
1278 // words WordZh and WordTw in the whole text
1279 if ( $manLevel[$v] == 'bidirectional' ) {
1280 $this->mConvTable[$v][$bidtable[$vo]] = $bidtable[$v];
1282 if ( $manLevel[$vo] == 'bidirectional' ) {
1283 $this->mConvTable[$vo][$bidtable[$v]] = $bidtable[$vo];
1288 /*for unidirectional array fill to convert tables */
1289 if ( ( $manLevel[$v] == 'bidirectional' || $manLevel[$v] == 'unidirectional' )
1290 && isset( $unidtable[$v] ) )
1292 if ( isset( $this->mConvTable[$v] ) ) {
1293 $this->mConvTable[$v] = array_merge( $this->mConvTable[$v], $unidtable[$v] );
1295 $this->mConvTable[$v] = $unidtable[$v];
1302 * Parse rules and flags.
1305 function parse( $variant = NULL ) {
1307 $variant = $this->mConverter->getPreferredVariant();
1310 $variants = $this->mConverter->mVariants;
1311 $this->parseFlags();
1312 $flags = $this->mFlags;
1314 // convert to specified variant
1315 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1316 if ( $this->mVariantFlags ) {
1317 // check if current variant in flags
1318 if ( isset( $this->mVariantFlags[$variant] ) ) {
1319 // then convert <text to convert> to current language
1320 $this->mRules = $this->mConverter->autoConvert( $this->mRules,
1322 } else { // if current variant no in flags,
1323 // then we check its fallback variants.
1325 $this->mConverter->getVariantFallbacks( $variant );
1326 foreach ( $variantFallbacks as $variantFallback ) {
1327 // if current variant's fallback exist in flags
1328 if ( isset( $this->mVariantFlags[$variantFallback] ) ) {
1329 // then convert <text to convert> to fallback language
1331 $this->mConverter->autoConvert( $this->mRules,
1337 $this->mFlags = $flags = array( 'R' => true );
1340 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1341 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1342 $this->mRules = str_replace( '=>', '=>', $this->mRules );
1343 $this->parseRules();
1345 $rules = $this->mRules;
1347 if ( !$this->mBidtable && !$this->mUnidtable ) {
1348 if ( isset( $flags['+'] ) || isset( $flags['-'] ) ) {
1349 // fill all variants if text in -{A/H/-|text} without rules
1350 foreach ( $this->mConverter->mVariants as $v ) {
1351 $this->mBidtable[$v] = $rules;
1353 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1354 $this->mFlags = $flags = array( 'R' => true );
1358 $this->mRuleDisplay = false;
1359 foreach ( $flags as $flag => $unused ) {
1362 // if we don't do content convert, still strip the -{}- tags
1363 $this->mRuleDisplay = $rules;
1366 // process N flag: output current variant name
1367 $ruleVar = trim( $rules );
1368 if ( isset( $this->mConverter->mVariantNames[$ruleVar] ) ) {
1369 $this->mRuleDisplay = $this->mConverter->mVariantNames[$ruleVar];
1371 $this->mRuleDisplay = '';
1375 // process D flag: output rules description
1376 $this->mRuleDisplay = $this->getRulesDesc();
1379 // process H,- flag or T only: output nothing
1380 $this->mRuleDisplay = '';
1383 $this->mRulesAction = 'remove';
1384 $this->mRuleDisplay = '';
1387 $this->mRulesAction = 'add';
1388 $this->mRuleDisplay = '';
1391 $this->mRuleDisplay = $this->getRuleConvertedStr( $variant );
1394 $this->mRuleTitle = $this->getRuleConvertedStr( $variant );
1395 $this->mRuleDisplay = '';
1398 // ignore unknown flags (but see error case below)
1401 if ( $this->mRuleDisplay === false ) {
1402 $this->mRuleDisplay = $this->mManualCodeError;
1405 $this->generateConvTable();
1411 function hasRules() {
1416 * Get display text on markup -{...}-
1419 function getDisplay() {
1420 return $this->mRuleDisplay;
1424 * Get converted title.
1427 function getTitle() {
1428 return $this->mRuleTitle;
1432 * Return how deal with conversion rules.
1435 function getRulesAction() {
1436 return $this->mRulesAction;
1440 * Get conversion table. ( bidirectional and unidirectional
1441 * conversion table )
1444 function getConvTable() {
1445 return $this->mConvTable;
1449 * Get conversion rules string.
1452 function getRules() {
1453 return $this->mRules;
1457 * Get conversion flags.
1460 function getFlags() {
1461 return $this->mFlags;