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 var $mNamespaceTables;
24 // 'bidirectional' 'unidirectional' 'disable' for each variant
29 var $mDescCodeSep = ':', $mDescVarSep = ';';
30 var $mUcfirst = false;
31 var $mConvRuleTitle = false;
36 var $mVarSeparatorPattern;
38 const CACHE_VERSION_KEY
= 'VERSION 6';
43 * @param $langobj The Language Object
44 * @param string $maincode the main language code of this language
45 * @param array $variants the supported variants of this language
46 * @param array $variantfallback the fallback language of each variant
47 * @param array $markup array defining the markup used for manual conversion
48 * @param array $flags array defining the custom strings that maps to the
50 * @param array $manualLevel limit for supported variants
53 function __construct( $langobj, $maincode,
55 $variantfallbacks = array(),
57 $manualLevel = array() ) {
58 $this->mLangObj
= $langobj;
59 $this->mMainLanguageCode
= $maincode;
61 global $wgDisabledVariants;
62 $this->mVariants
= array();
63 foreach ( $variants as $variant ) {
64 if ( !in_array( $variant, $wgDisabledVariants ) ) {
65 $this->mVariants
[] = $variant;
68 $this->mVariantFallbacks
= $variantfallbacks;
69 global $wgLanguageNames;
70 $this->mVariantNames
= $wgLanguageNames;
71 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
73 // 'S' show converted text
74 // '+' add rules for alltext
75 // 'E' the gave flags is error
76 // these flags above are reserved for program
77 'A' => 'A', // add rule for convert code (all text convert)
78 'T' => 'T', // title convert
79 'R' => 'R', // raw content
80 'D' => 'D', // convert description (subclass implement)
81 '-' => '-', // remove convert (not implement)
82 'H' => 'H', // add rule for convert code
83 // (but no display in placed code )
84 'N' => 'N' // current variant name
86 $this->mFlags
= array_merge( $f, $flags );
87 foreach ( $this->mVariants
as $v ) {
88 if ( array_key_exists( $v, $manualLevel ) ) {
89 $this->mManualLevel
[$v] = $manualLevel[$v];
91 $this->mManualLevel
[$v] = 'bidirectional';
93 $this->mNamespaceTables
[$v] = array();
94 $this->mFlags
[$v] = $v;
101 function getVariants() {
102 return $this->mVariants
;
106 * In case some variant is not defined in the markup, we need
107 * to have some fallback. For example, in zh, normally people
108 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
109 * when zh-sg is preferred but not defined, we will pick zh-hans
110 * in this case. Right now this is only used by zh.
112 * @param string $v The language code of the variant
113 * @return string array The code of the fallback language or false if there
117 function getVariantFallbacks( $v ) {
118 if ( isset( $this->mVariantFallbacks
[$v] ) ) {
119 return $this->mVariantFallbacks
[$v];
121 return $this->mMainLanguageCode
;
125 * Get the title produced by the conversion rule.
128 function getConvRuleTitle() {
129 return $this->mConvRuleTitle
;
133 * Get preferred language variants.
134 * @param boolean $fromUser Get it from $wgUser's preferences
135 * @param boolean $fromHeader Get it from Accept-Language
136 * @return string the preferred language code
139 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
140 global $wgDefaultLanguageVariant;
142 $req = $this->getURLVariant();
144 if ( $fromUser && !$req ) {
145 $req = $this->getUserVariant();
148 if ( $fromHeader && !$req ) {
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 * Validate the variant
168 * @param string $v the variant to validate
169 * @returns mixed returns the variant if it is valid, null otherwise
171 function validateVariant( $v = null ) {
172 if ( $v !== null && in_array( $v, $this->mVariants
) ) {
179 * Get the variant specified in the URL
181 * @returns mixed variant if one found, false otherwise.
183 function getURLVariant() {
187 if ( $this->mURLVariant
) {
188 return $this->mURLVariant
;
191 // see if the preference is set in the request
192 $ret = $wgRequest->getText( 'variant' );
195 $ret = $wgRequest->getVal( 'uselang' );
198 return $this->mURLVariant
= $this->validateVariant( $ret );
202 * Determine if the user has a variant set.
204 * @returns mixed variant if one found, false otherwise.
206 function getUserVariant() {
210 // memoizing this function wreaks havoc on parserTest.php
211 /* if ( $this->mUserVariant ) { */
212 /* return $this->mUserVariant; */
215 // get language variant preference from logged in users
216 // Don't call this on stub objects because that causes infinite
217 // recursion during initialisation
218 if ( $wgUser->isLoggedIn() ) {
219 $ret = $wgUser->getOption( 'variant' );
222 // figure out user lang without constructing wgLang to avoid
223 // infinite recursion
224 $ret = $wgUser->getOption( 'language' );
227 return $this->mUserVariant
= $this->validateVariant( $ret );
232 * Determine the language variant from the Accept-Language header.
234 * @returns mixed variant if one found, false otherwise.
236 function getHeaderVariant() {
240 if ( $this->mHeaderVariant
) {
241 return $this->mHeaderVariant
;
244 // see if some supported language variant is set in the
247 $acceptLanguage = $wgRequest->getHeader( 'Accept-Language' );
248 if ( !$acceptLanguage ) {
253 $result = StringUtils
::explode( ',', strtolower( $acceptLanguage ) );
254 $languages = array();
256 foreach ( $result as $elem ) {
257 // if $elem likes 'zh-cn;q=0.9'
258 if ( ( $posi = strpos( $elem, ';' ) ) !== false ) {
259 // get the real language code likes 'zh-cn'
260 $languages[] = substr( $elem, 0, $posi );
262 $languages[] = $elem;
266 $fallback_languages = array();
267 foreach ( $languages as $language ) {
269 $language = trim( $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 * Caption convert, base on preg_replace_callback.
305 * To convert text in "title" or "alt", like '<img alt="text" ... '
306 * or '<span title="text" ... '
308 * @return string like ' alt="yyyy"' or ' title="yyyy"'
311 function captionConvert( $matches ) {
312 $toVariant = $this->getPreferredVariant();
313 $title = $matches[1];
315 // we convert captions except URL
316 if ( !strpos( $text, '://' ) ) {
317 $text = $this->translate( $text, $toVariant );
319 return " $title=\"$text\"";
323 * Dictionary-based conversion.
325 * @param string $text the text to be converted
326 * @param string $toVariant the target language code
327 * @return string the converted text
330 function autoConvert( $text, $toVariant = false ) {
331 $fname = 'LanguageConverter::autoConvert';
333 wfProfileIn( $fname );
335 if ( !$this->mTablesLoaded
) {
340 $toVariant = $this->getPreferredVariant();
346 /* we convert everything except:
347 1. html markups (anything between < and >)
349 3. place holders created by the parser
352 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
353 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
358 // this one is needed when the text is inside an html markup
359 $htmlfix = '|<[^>]+$|^[^<>]*>';
361 // disable convert to variants between <code></code> tags
362 $codefix = '<code>.+?<\/code>|';
363 // disable convertsion of <script type="text/javascript"> ... </script>
364 $scriptfix = '<script.*?>.*?<\/script>|';
365 // disable conversion of <pre xxxx> ... </pre>
366 $prefix = '<pre.*?>.*?<\/pre>|';
368 $reg = '/' . $codefix . $scriptfix . $prefix .
369 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
371 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
373 $m = array_shift( $matches );
375 $ret = $this->translate( $m[0], $toVariant );
376 $mstart = $m[1] +
strlen( $m[0] );
378 // enable convertsion of '<img alt="xxxx" ... '
379 // or '<span title="xxxx" ... '
380 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
385 foreach ( $matches as $m ) {
386 $mark = substr( $text, $mstart, $m[1] - $mstart );
387 $mark = preg_replace_callback( $captionpattern,
388 array( &$this, 'captionConvert' ),
390 // Let's convert the trtext only once,
391 // it would give us more performance improvement
393 $trtext .= $m[0] . $trtextmark;
394 $mstart = $m[1] +
strlen( $m[0] );
397 $trtext = $this->translate( $trtext, $toVariant );
398 $trtext = StringUtils
::explode( $trtextmark, $trtext );
399 foreach ( $trtext as $t ) {
400 $ret .= array_shift( $notrtext );
403 wfProfileOut( $fname );
408 * Translate a string to a variant.
409 * Doesn't process markup or do any of that other stuff, for that use
412 * @param string $text Text to convert
413 * @param string $variant Variant language code
414 * @return string Translated text
417 function translate( $text, $variant ) {
418 wfProfileIn( __METHOD__
);
419 // If $text is empty or only includes spaces, do nothing
420 // Otherwise translate it
421 if ( trim( $text ) ) {
422 if ( !$this->mTablesLoaded
) {
425 $text = $this->mTables
[$variant]->replace( $text );
427 wfProfileOut( __METHOD__
);
432 * Convert text to all supported variants.
434 * @param string $text the text to be converted
435 * @return array of string
438 function autoConvertToAllVariants( $text ) {
439 $fname = 'LanguageConverter::autoConvertToAllVariants';
440 wfProfileIn( $fname );
441 if ( !$this->mTablesLoaded
) {
446 foreach ( $this->mVariants
as $variant ) {
447 $ret[$variant] = $this->translate( $text, $variant );
450 wfProfileOut( $fname );
455 * Convert link text to all supported variants.
457 * @param string $text the text to be converted
458 * @return array of string
461 function convertLinkToAllVariants( $text ) {
462 if ( !$this->mTablesLoaded
) {
467 $tarray = StringUtils
::explode( '-{', $text );
470 foreach ( $tarray as $txt ) {
473 foreach ( $this->mVariants
as $variant ) {
474 $ret[$variant] = $this->translate( $txt, $variant );
479 $marked = explode( '}-', $txt, 2 );
481 foreach ( $this->mVariants
as $variant ) {
482 $ret[$variant] .= '-{' . $marked[0] . '}-';
483 if ( array_key_exists( 1, $marked ) ) {
484 $ret[$variant] .= $this->translate( $marked[1], $variant );
494 * Prepare manual conversion table.
497 function applyManualConv( $convRule ) {
498 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom
499 // conversion in title
500 $this->mConvRuleTitle
= $convRule->getTitle();
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 );
527 * @param string $title the title included namespace
528 * @return array of string
531 function convertNamespace( $title, $variant ) {
532 $splittitle = explode( ':', $title, 2 );
533 if ( count( $splittitle ) < 2 ) {
536 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) ) {
537 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
539 $ret = implode( ':', $splittitle );
544 * Convert text to different variants of a language. The automatic
545 * conversion is done in autoConvert(). Here we parse the text
546 * marked with -{}-, which specifies special conversions of the
547 * text that can not be accomplished in autoConvert().
549 * Syntax of the markup:
550 * -{code1:text1;code2:text2;...}- or
551 * -{flags|code1:text1;code2:text2;...}- or
552 * -{text}- in which case no conversion should take place for text
554 * @param string $text text to be converted
555 * @return string converted text
558 function convert( $text ) {
559 global $wgDisableLangConversion;
560 if ( $wgDisableLangConversion ) return $text;
562 $variant = $this->getPreferredVariant();
564 return $this->recursiveConvertTopLevel( $text, $variant );
567 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
570 $length = strlen( $text );
571 while ( $startPos < $length ) {
573 $pos = strpos( $text, '-{', $startPos );
575 if ( $pos === false ) {
576 // No more markup, append final segment
577 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
583 // Append initial segment
584 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
589 // Do recursive conversion
590 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
596 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
597 // Quick sanity check (no function calls)
598 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
599 throw new MWException( __METHOD__
.': invalid input string' );
604 $warningDone = false;
605 $length = strlen( $text );
607 while ( $startPos < $length ) {
609 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
619 // Append initial segment
620 $inner .= substr( $text, $startPos, $pos - $startPos );
628 if ( $depth >= $this->mMaxDepth
) {
630 if ( !$warningDone ) {
631 $inner .= '<span class="error">' .
632 wfMsgForContent( 'language-converter-depth-warning',
640 // Recursively parse another rule
641 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
646 $rule = new ConverterRule( $inner, $this );
647 $rule->parse( $variant );
648 $this->applyManualConv( $rule );
649 return $rule->getDisplay();
651 throw new MWException( __METHOD__
.': invalid regex match' );
656 if ( $startPos < $length ) {
657 $inner .= substr( $text, $startPos );
660 return '-{' . $this->autoConvert( $inner, $variant );
664 * If a language supports multiple variants, it is
665 * possible that non-existing link in one variant
666 * actually exists in another variant. This function
667 * tries to find it. See e.g. LanguageZh.php
669 * @param string $link the name of the link
670 * @param mixed $nt the title object of the link
671 * @param boolean $ignoreOtherCond: to disable other conditions when
672 * we need to transclude a template or update a category's link
673 * @return null the input parameters may be modified upon return
676 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
677 # If the article has already existed, there is no need to
678 # check it again, otherwise it may cause a fault.
679 if ( is_object( $nt ) && $nt->exists() ) {
683 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
685 $isredir = $wgRequest->getText( 'redirect', 'yes' );
686 $action = $wgRequest->getText( 'action' );
687 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
688 $disableLinkConversion = $wgDisableLangConversion
689 ||
$wgDisableTitleConversion;
690 $linkBatch = new LinkBatch();
694 if ( $disableLinkConversion ||
695 ( !$ignoreOtherCond &&
698 ||
$action == 'submit'
699 ||
$linkconvert == 'no'
700 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
704 if ( is_object( $nt ) ) {
705 $ns = $nt->getNamespace();
708 $variants = $this->autoConvertToAllVariants( $link );
709 if ( $variants == false ) { // give up
715 foreach ( $variants as $v ) {
717 $varnt = Title
::newFromText( $v, $ns );
718 if ( !is_null( $varnt ) ) {
719 $linkBatch->addObj( $varnt );
725 // fetch all variants in single query
726 $linkBatch->execute();
728 foreach ( $titles as $varnt ) {
729 if ( $varnt->getArticleID() > 0 ) {
731 $link = $varnt->getText();
738 * Returns language specific hash options.
742 function getExtraHashOptions() {
743 $variant = $this->getPreferredVariant();
744 return '!' . $variant ;
748 * Load default conversion tables.
749 * This method must be implemented in derived class.
753 function loadDefaultTables() {
754 $name = get_class( $this );
755 wfDie( "Must implement loadDefaultTables() method in class $name" );
759 * Load conversion tables either from the cache or the disk.
762 function loadTables( $fromcache = true ) {
764 if ( $this->mTablesLoaded
) {
767 wfProfileIn( __METHOD__
);
768 $this->mTablesLoaded
= true;
769 $this->mTables
= false;
771 wfProfileIn( __METHOD__
. '-cache' );
772 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
773 wfProfileOut( __METHOD__
. '-cache' );
776 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
777 wfProfileIn( __METHOD__
. '-recache' );
778 // not in cache, or we need a fresh reload.
779 // we will first load the default tables
780 // then update them using things in MediaWiki:Zhconversiontable/*
781 $this->loadDefaultTables();
782 foreach ( $this->mVariants
as $var ) {
783 $cached = $this->parseCachedTable( $var );
784 $this->mTables
[$var]->mergeArray( $cached );
787 $this->postLoadTables();
788 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
790 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
791 wfProfileOut( __METHOD__
. '-recache' );
793 wfProfileOut( __METHOD__
);
797 * Hook for post processig after conversion tables are loaded.
800 function postLoadTables() { }
803 * Reload the conversion tables.
807 function reloadTables() {
808 if ( $this->mTables
) {
809 unset( $this->mTables
);
811 $this->mTablesLoaded
= false;
812 $this->loadTables( false );
817 * Parse the conversion table stored in the cache.
819 * The tables should be in blocks of the following form:
826 * To make the tables more manageable, subpages are allowed
827 * and will be parsed recursively if $recursive == true.
830 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
831 global $wgMessageCache;
832 static $parsed = array();
834 if ( !is_object( $wgMessageCache ) ) {
838 $key = 'Conversiontable/' . $code;
840 $key .= '/' . $subpage;
842 if ( array_key_exists( $key, $parsed ) ) {
846 if ( strpos( $code, '/' ) === false ) {
847 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
849 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
850 "Conversiontable/$code" );
851 if ( $title && $title->exists() ) {
852 $article = new Article( $title );
853 $txt = $article->getContents();
859 // get all subpage links of the form
860 // [[MediaWiki:conversiontable/zh-xx/...|...]]
861 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
863 $subs = StringUtils
::explode( '[[', $txt );
865 foreach ( $subs as $sub ) {
866 $link = explode( ']]', $sub, 2 );
867 if ( count( $link ) != 2 ) {
870 $b = explode( '|', $link[0], 2 );
871 $b = explode( '/', trim( $b[0] ), 3 );
872 if ( count( $b ) == 3 ) {
878 if ( $b[0] == $linkhead && $b[1] == $code ) {
879 $sublinks[] = $sublink;
884 // parse the mappings in this page
885 $blocks = StringUtils
::explode( '-{', $txt );
888 foreach ( $blocks as $block ) {
890 // Skip the part before the first -{
894 $mappings = explode( '}-', $block, 2 );
895 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
897 $table = StringUtils
::explode( ';', $stripped );
898 foreach ( $table as $t ) {
899 $m = explode( '=>', $t, 3 );
900 if ( count( $m ) != 2 )
902 // trim any trailling comments starting with '//'
903 $tt = explode( '//', $m[1], 2 );
904 $ret[trim( $m[0] )] = trim( $tt[0] );
907 $parsed[$key] = true;
910 // recursively parse the subpages
912 foreach ( $sublinks as $link ) {
913 $s = $this->parseCachedTable( $code, $link, $recursive );
914 $ret = array_merge( $ret, $s );
918 if ( $this->mUcfirst
) {
919 foreach ( $ret as $k => $v ) {
920 $ret[Language
::ucfirst( $k )] = Language
::ucfirst( $v );
927 * Enclose a string with the "no conversion" tag. This is used by
928 * various functions in the Parser.
930 * @param string $text text to be tagged for no conversion
931 * @return string the tagged text
934 function markNoConversion( $text, $noParse = false ) {
935 # don't mark if already marked
936 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
940 $ret = "-{R|$text}-";
945 * Convert the sorting key for category links. This should make different
946 * keys that are variants of each other map to the same key.
948 function convertCategoryKey( $key ) {
953 * Hook to refresh the cache of conversion tables when
954 * MediaWiki:conversiontable* is updated.
957 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
958 $iswatch, $section, $flags, $revision ) {
959 $titleobj = $article->getTitle();
960 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
961 $title = $titleobj->getDBkey();
962 $t = explode( '/', $title, 3 );
964 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
965 if ( $this->validateVariant( $t[1] ) ) {
966 $this->reloadTables();
974 * Armour rendered math against conversion.
975 * Wrap math into rawoutput -{R| math }- syntax.
978 function armourMath( $text ) {
979 // we need to convert '-{' and '}-' to '-{' and '}-'
980 // to avoid a unwanted '}-' appeared after the math-image.
981 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
982 $ret = "-{R|$text}-";
987 * Get the cached separator pattern for ConverterRule::parseRules()
989 function getVarSeparatorPattern() {
990 if ( is_null( $this->mVarSeparatorPattern
) ) {
991 // varsep_pattern for preg_split:
992 // text should be splited by ";" only if a valid variant
993 // name exist after the markup, for example:
994 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
995 // <span style="font-size:120%;">yyy</span>;}-
996 // we should split it as:
998 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
999 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1003 foreach ( $this->mVariants
as $variant ) {
1004 // zh-hans:xxx;zh-hant:yyy
1005 $pat .= $variant . '\s*:|';
1006 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1007 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1010 $this->mVarSeparatorPattern
= $pat;
1012 return $this->mVarSeparatorPattern
;
1017 * Parser for rules of language conversion , parse rules in -{ }- tag.
1019 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1021 class ConverterRule
{
1022 var $mText; // original text in -{text}-
1023 var $mConverter; // LanguageConverter object
1024 var $mManualCodeError = '<strong class="error">code error!</strong>';
1025 var $mRuleDisplay = '';
1026 var $mRuleTitle = false;
1027 var $mRules = '';// string : the text of the rules
1028 var $mRulesAction = 'none';
1029 var $mFlags = array();
1030 var $mVariantFlags = array();
1031 var $mConvTable = array();
1032 var $mBidtable = array();// array of the translation in each variant
1033 var $mUnidtable = array();// array of the translation in each variant
1038 * @param string $text the text between -{ and }-
1039 * @param object $converter a LanguageConverter object
1042 function __construct( $text, $converter ) {
1043 $this->mText
= $text;
1044 $this->mConverter
= $converter;
1048 * Check if variants array in convert array.
1050 * @param string $variant Variant language code
1051 * @return string Translated text
1054 function getTextInBidtable( $variants ) {
1055 $variants = (array)$variants;
1059 foreach ( $variants as $variant ) {
1060 if ( isset( $this->mBidtable
[$variant] ) ) {
1061 return $this->mBidtable
[$variant];
1068 * Parse flags with syntax -{FLAG| ... }-
1071 function parseFlags() {
1072 $text = $this->mText
;
1074 $variantFlags = array();
1076 $sepPos = strpos( $text, '|' );
1077 if ( $sepPos !== false ) {
1078 $validFlags = $this->mConverter
->mFlags
;
1079 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1080 foreach ( $f as $ff ) {
1082 if ( isset( $validFlags[$ff] ) ) {
1083 $flags[$validFlags[$ff]] = true;
1086 $text = strval( substr( $text, $sepPos +
1 ) );
1091 } elseif ( isset( $flags['R'] ) ) {
1092 $flags = array( 'R' => true );// remove other flags
1093 } elseif ( isset( $flags['N'] ) ) {
1094 $flags = array( 'N' => true );// remove other flags
1095 } elseif ( isset( $flags['-'] ) ) {
1096 $flags = array( '-' => true );// remove other flags
1097 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1099 } elseif ( isset( $flags['H'] ) ) {
1100 // replace A flag, and remove other flags except T
1101 $temp = array( '+' => true, 'H' => true );
1102 if ( isset( $flags['T'] ) ) {
1105 if ( isset( $flags['D'] ) ) {
1110 if ( isset( $flags['A'] ) ) {
1114 if ( isset( $flags['D'] ) ) {
1115 unset( $flags['S'] );
1117 // try to find flags like "zh-hans", "zh-hant"
1118 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1119 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1120 if ( $variantFlags ) {
1121 $variantFlags = array_flip( $variantFlags );
1125 $this->mVariantFlags
= $variantFlags;
1126 $this->mRules
= $text;
1127 $this->mFlags
= $flags;
1131 * Generate conversion table.
1134 function parseRules() {
1135 $rules = $this->mRules
;
1136 $flags = $this->mFlags
;
1137 $bidtable = array();
1138 $unidtable = array();
1139 $variants = $this->mConverter
->mVariants
;
1140 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1142 $choice = preg_split( $varsep_pattern, $rules );
1144 foreach ( $choice as $c ) {
1145 $v = explode( ':', $c, 2 );
1146 if ( count( $v ) != 2 ) {
1147 // syntax error, skip
1150 $to = trim( $v[1] );
1152 $u = explode( '=>', $v, 2 );
1153 // if $to is empty, strtr() could return a wrong result
1154 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1155 $bidtable[$v] = $to;
1156 } elseif ( count( $u ) == 2 ) {
1157 $from = trim( $u[0] );
1159 if ( array_key_exists( $v, $unidtable )
1160 && !is_array( $unidtable[$v] )
1162 && in_array( $v, $variants ) ) {
1163 $unidtable[$v] = array( $from => $to );
1164 } elseif ( $to && in_array( $v, $variants ) ) {
1165 $unidtable[$v][$from] = $to;
1168 // syntax error, pass
1169 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1170 $bidtable = array();
1171 $unidtable = array();
1175 $this->mBidtable
= $bidtable;
1176 $this->mUnidtable
= $unidtable;
1182 function getRulesDesc() {
1183 $codesep = $this->mConverter
->mDescCodeSep
;
1184 $varsep = $this->mConverter
->mDescVarSep
;
1186 foreach ( $this->mBidtable
as $k => $v ) {
1187 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1189 foreach ( $this->mUnidtable
as $k => $a ) {
1190 foreach ( $a as $from => $to ) {
1191 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1192 "$codesep$to$varsep";
1199 * Parse rules conversion.
1202 function getRuleConvertedStr( $variant ) {
1203 $bidtable = $this->mBidtable
;
1204 $unidtable = $this->mUnidtable
;
1206 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1207 return $this->mRules
;
1209 // display current variant in bidirectional array
1210 $disp = $this->getTextInBidtable( $variant );
1211 // or display current variant in fallbacks
1213 $disp = $this->getTextInBidtable(
1214 $this->mConverter
->getVariantFallbacks( $variant ) );
1216 // or display current variant in unidirectional array
1217 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1218 $disp = array_values( $unidtable[$variant] );
1221 // or display frist text under disable manual convert
1223 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1224 if ( count( $bidtable ) > 0 ) {
1225 $disp = array_values( $bidtable );
1228 $disp = array_values( $unidtable );
1229 $disp = array_values( $disp[0] );
1238 * Generate conversion table for all text.
1241 function generateConvTable() {
1242 // Special case optimisation
1243 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1244 $this->mConvTable
= array();
1248 $bidtable = $this->mBidtable
;
1249 $unidtable = $this->mUnidtable
;
1250 $manLevel = $this->mConverter
->mManualLevel
;
1253 foreach ( $this->mConverter
->mVariants
as $v ) {
1254 /* for bidirectional array
1255 fill in the missing variants, if any,
1257 if ( !isset( $bidtable[$v] ) ) {
1259 $this->mConverter
->getVariantFallbacks( $v );
1260 $vf = $this->getTextInBidtable( $variantFallbacks );
1262 $bidtable[$v] = $vf;
1266 if ( isset( $bidtable[$v] ) ) {
1267 foreach ( $vmarked as $vo ) {
1268 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1269 // or -{H|zh:WordZh;zh-tw:WordTw}-
1270 // or -{-|zh:WordZh;zh-tw:WordTw}-
1271 // to introduce a custom mapping between
1272 // words WordZh and WordTw in the whole text
1273 if ( $manLevel[$v] == 'bidirectional' ) {
1274 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1276 if ( $manLevel[$vo] == 'bidirectional' ) {
1277 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1282 /*for unidirectional array fill to convert tables */
1283 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1284 && isset( $unidtable[$v] ) )
1286 if ( isset( $this->mConvTable
[$v] ) ) {
1287 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1289 $this->mConvTable
[$v] = $unidtable[$v];
1296 * Parse rules and flags.
1299 function parse( $variant = NULL ) {
1301 $variant = $this->mConverter
->getPreferredVariant();
1304 $variants = $this->mConverter
->mVariants
;
1305 $this->parseFlags();
1306 $flags = $this->mFlags
;
1308 // convert to specified variant
1309 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1310 if ( $this->mVariantFlags
) {
1311 // check if current variant in flags
1312 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1313 // then convert <text to convert> to current language
1314 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1316 } else { // if current variant no in flags,
1317 // then we check its fallback variants.
1319 $this->mConverter
->getVariantFallbacks( $variant );
1320 foreach ( $variantFallbacks as $variantFallback ) {
1321 // if current variant's fallback exist in flags
1322 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1323 // then convert <text to convert> to fallback language
1325 $this->mConverter
->autoConvert( $this->mRules
,
1331 $this->mFlags
= $flags = array( 'R' => true );
1334 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1335 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1336 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1337 $this->parseRules();
1339 $rules = $this->mRules
;
1341 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1342 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1343 // fill all variants if text in -{A/H/-|text} without rules
1344 foreach ( $this->mConverter
->mVariants
as $v ) {
1345 $this->mBidtable
[$v] = $rules;
1347 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1348 $this->mFlags
= $flags = array( 'R' => true );
1352 $this->mRuleDisplay
= false;
1353 foreach ( $flags as $flag => $unused ) {
1356 // if we don't do content convert, still strip the -{}- tags
1357 $this->mRuleDisplay
= $rules;
1360 // process N flag: output current variant name
1361 $ruleVar = trim( $rules );
1362 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1363 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1365 $this->mRuleDisplay
= '';
1369 // process D flag: output rules description
1370 $this->mRuleDisplay
= $this->getRulesDesc();
1373 // process H,- flag or T only: output nothing
1374 $this->mRuleDisplay
= '';
1377 $this->mRulesAction
= 'remove';
1378 $this->mRuleDisplay
= '';
1381 $this->mRulesAction
= 'add';
1382 $this->mRuleDisplay
= '';
1385 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1388 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1389 $this->mRuleDisplay
= '';
1392 // ignore unknown flags (but see error case below)
1395 if ( $this->mRuleDisplay
=== false ) {
1396 $this->mRuleDisplay
= $this->mManualCodeError
;
1399 $this->generateConvTable();
1405 function hasRules() {
1410 * Get display text on markup -{...}-
1413 function getDisplay() {
1414 return $this->mRuleDisplay
;
1418 * Get converted title.
1421 function getTitle() {
1422 return $this->mRuleTitle
;
1426 * Return how deal with conversion rules.
1429 function getRulesAction() {
1430 return $this->mRulesAction
;
1434 * Get conversion table. ( bidirectional and unidirectional
1435 * conversion table )
1438 function getConvTable() {
1439 return $this->mConvTable
;
1443 * Get conversion rules string.
1446 function getRules() {
1447 return $this->mRules
;
1451 * Get conversion flags.
1454 function getFlags() {
1455 return $this->mFlags
;