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
30 var $mDescCodeSep = ':', $mDescVarSep = ';';
31 var $mUcfirst = false;
32 var $mConvRuleTitle = false;
37 const CACHE_VERSION_KEY
= 'VERSION 6';
42 * @param $langobj The Language Object
43 * @param string $maincode the main language code of this language
44 * @param array $variants the supported variants of this language
45 * @param array $variantfallback the fallback language of each variant
46 * @param array $markup array defining the markup used for manual conversion
47 * @param array $flags array defining the custom strings that maps to the
49 * @param array $manualLevel limit for supported variants
52 function __construct( $langobj, $maincode,
54 $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 );
75 'unidsep' => '=>', // for unidirectional conversion
80 $this->mMarkup
= array_merge( $m, $markup );
82 // 'S' show converted text
83 // '+' add rules for alltext
84 // 'E' the gave flags is error
85 // these flags above are reserved for program
86 'A' => 'A', // add rule for convert code (all text convert)
87 'T' => 'T', // title convert
88 'R' => 'R', // raw content
89 'D' => 'D', // convert description (subclass implement)
90 '-' => '-', // remove convert (not implement)
91 'H' => 'H', // add rule for convert code
92 // (but no display in placed code )
93 'N' => 'N' // current variant name
95 $this->mFlags
= array_merge( $f, $flags );
96 foreach ( $this->mVariants
as $v ) {
97 if ( array_key_exists( $v, $manualLevel ) ) {
98 $this->mManualLevel
[$v] = $manualLevel[$v];
100 $this->mManualLevel
[$v] = 'bidirectional';
102 $this->mNamespaceTables
[$v] = array();
103 $this->mFlags
[$v] = $v;
110 function getVariants() {
111 return $this->mVariants
;
115 * In case some variant is not defined in the markup, we need
116 * to have some fallback. For example, in zh, normally people
117 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
118 * when zh-sg is preferred but not defined, we will pick zh-hans
119 * in this case. Right now this is only used by zh.
121 * @param string $v The language code of the variant
122 * @return string array The code of the fallback language or false if there
126 function getVariantFallbacks( $v ) {
127 if ( array_key_exists( $v, $this->mVariantFallbacks
) ) {
128 return $this->mVariantFallbacks
[$v];
130 return $this->mMainLanguageCode
;
134 * Get preferred language variants.
135 * @param boolean $fromUser Get it from $wgUser's preferences
136 * @param boolean $fromHeader Get it from Accept-Language
137 * @return string the preferred language code
140 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
141 global $wgDefaultLanguageVariant;
143 $req = $this->getURLVariant();
145 if ( $fromUser && !$req ) {
146 $req = $this->getUserVariant();
149 if ( $fromHeader && !$req ) {
150 $req = $this->getHeaderVariant();
153 if ( $wgDefaultLanguageVariant && !$req ) {
154 $req = $this->validateVariant( $wgDefaultLanguageVariant );
157 // This function, unlike the other get*Variant functions, is
158 // not memoized (i.e. there return value is not cached) since
159 // new information might appear during processing after this
164 return $this->mMainLanguageCode
;
168 * Validate the variant
169 * @param string $v the variant to validate
170 * @returns mixed returns the variant if it is valid, null otherwise
172 function validateVariant( $v = null ) {
173 if ( $v !== null && in_array( $v, $this->mVariants
) ) {
180 * Get the variant specified in the URL
182 * @returns mixed variant if one found, false otherwise.
184 function getURLVariant() {
188 if ( $this->mURLVariant
) {
189 return $this->mURLVariant
;
192 // see if the preference is set in the request
193 $ret = $wgRequest->getText( 'variant' );
196 $ret = $wgRequest->getVal( 'uselang' );
199 return $this->mURLVariant
= $this->validateVariant( $ret );
203 * Determine if the user has a variant set.
205 * @returns mixed variant if one found, false otherwise.
207 function getUserVariant() {
211 // memoizing this function wreaks havoc on parserTest.php
212 /* if ( $this->mUserVariant ) { */
213 /* return $this->mUserVariant; */
216 // get language variant preference from logged in users
217 // Don't call this on stub objects because that causes infinite
218 // recursion during initialisation
219 if ( $wgUser->isLoggedIn() ) {
220 $ret = $wgUser->getOption( 'variant' );
223 // figure out user lang without constructing wgLang to avoid
224 // infinite recursion
225 $ret = $wgUser->getOption( 'language' );
228 return $this->mUserVariant
= $this->validateVariant( $ret );
233 * Determine the language variant from the Accept-Language header.
235 * @returns mixed variant if one found, false otherwise.
237 function getHeaderVariant() {
241 if ( $this->mHeaderVariant
) {
242 return $this->mHeaderVariant
;
245 // see if some supported language variant is set in the
248 $acceptLanguage = $wgRequest->getHeader( 'Accept-Language' );
249 if ( !$acceptLanguage ) {
254 $result = explode( ',', strtolower( $acceptLanguage ) );
255 $languages = array();
257 foreach ( $result as $elem ) {
258 // if $elem likes 'zh-cn;q=0.9'
259 if ( ( $posi = strpos( $elem, ';' ) ) !== false ) {
260 // get the real language code likes 'zh-cn'
261 $languages[] = substr( $elem, 0, $posi );
263 $languages[] = $elem;
267 $fallback_languages = array();
268 foreach ( $languages as $language ) {
270 $language = trim( $language );
271 $this->mHeaderVariant
= $this->validateVariant( $language );
272 if ( $this->mHeaderVariant
) {
276 // To see if there are fallbacks of current language.
277 // We record these fallback variants, and process
279 $fallbacks = $this->getVariantFallbacks( $language );
280 if ( is_string( $fallbacks ) ) {
281 $fallback_languages[] = $fallbacks;
282 } elseif ( is_array( $fallbacks ) ) {
283 $fallback_languages =
284 array_merge( $fallback_languages,
289 if ( !$this->mHeaderVariant
) {
290 // process fallback languages now
291 $fallback_languages = array_unique( $fallback_languages );
292 foreach ( $fallback_languages as $language ) {
293 $this->mHeaderVariant
= $this->validateVariant( $language );
294 if ( $this->mHeaderVariant
) {
300 return $this->mHeaderVariant
;
304 * Caption convert, base on preg_replace_callback.
306 * To convert text in "title" or "alt", like '<img alt="text" ... '
307 * or '<span title="text" ... '
309 * @return string like ' alt="yyyy"' or ' title="yyyy"'
312 function captionConvert( $matches ) {
313 $toVariant = $this->getPreferredVariant();
314 $title = $matches[1];
316 // we convert captions except URL
317 if ( !strpos( $text, '://' ) ) {
318 $text = $this->translate( $text, $toVariant );
320 return " $title=\"$text\"";
324 * Dictionary-based conversion.
326 * @param string $text the text to be converted
327 * @param string $toVariant the target language code
328 * @return string the converted text
331 function autoConvert( $text, $toVariant = false ) {
332 $fname = 'LanguageConverter::autoConvert';
334 wfProfileIn( $fname );
336 if ( !$this->mTablesLoaded
) {
341 $toVariant = $this->getPreferredVariant();
347 /* we convert everything except:
348 1. html markups (anything between < and >)
350 3. place holders created by the parser
353 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
354 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
359 // this one is needed when the text is inside an html markup
360 $htmlfix = '|<[^>]+$|^[^<>]*>';
362 // disable convert to variants between <code></code> tags
363 $codefix = '<code>.+?<\/code>|';
364 // disable convertsion of <script type="text/javascript"> ... </script>
365 $scriptfix = '<script.*?>.*?<\/script>|';
366 // disable conversion of <pre xxxx> ... </pre>
367 $prefix = '<pre.*?>.*?<\/pre>|';
369 $reg = '/' . $codefix . $scriptfix . $prefix .
370 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
372 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
374 $m = array_shift( $matches );
376 $ret = $this->translate( $m[0], $toVariant );
377 $mstart = $m[1] +
strlen( $m[0] );
379 // enable convertsion of '<img alt="xxxx" ... '
380 // or '<span title="xxxx" ... '
381 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
386 foreach ( $matches as $m ) {
387 $mark = substr( $text, $mstart, $m[1] - $mstart );
388 $mark = preg_replace_callback( $captionpattern,
389 array( &$this, 'captionConvert' ),
391 // Let's convert the trtext only once,
392 // it would give us more performance improvement
394 $trtext .= $m[0] . $trtextmark;
395 $mstart = $m[1] +
strlen( $m[0] );
398 $trtext = $this->translate( $trtext, $toVariant );
399 $trtext = StringUtils
::explode( $trtextmark, $trtext );
400 foreach ( $trtext as $t ) {
401 $ret .= array_shift( $notrtext );
404 wfProfileOut( $fname );
409 * Translate a string to a variant.
410 * Doesn't process markup or do any of that other stuff, for that use
413 * @param string $text Text to convert
414 * @param string $variant Variant language code
415 * @return string Translated text
418 function translate( $text, $variant ) {
419 wfProfileIn( __METHOD__
);
420 // If $text is empty or only includes spaces, do nothing
421 // Otherwise translate it
422 if ( trim( $text ) ) {
423 if ( !$this->mTablesLoaded
) {
426 $text = $this->mTables
[$variant]->replace( $text );
428 wfProfileOut( __METHOD__
);
433 * Convert text to all supported variants.
435 * @param string $text the text to be converted
436 * @return array of string
439 function autoConvertToAllVariants( $text ) {
440 $fname = 'LanguageConverter::autoConvertToAllVariants';
441 wfProfileIn( $fname );
442 if ( !$this->mTablesLoaded
) {
447 foreach ( $this->mVariants
as $variant ) {
448 $ret[$variant] = $this->translate( $text, $variant );
451 wfProfileOut( $fname );
456 * Convert link text to all supported variants.
458 * @param string $text the text to be converted
459 * @return array of string
462 function convertLinkToAllVariants( $text ) {
463 if ( !$this->mTablesLoaded
) {
468 $tarray = explode( $this->mMarkup
['begin'], $text );
469 $tfirst = array_shift( $tarray );
471 foreach ( $this->mVariants
as $variant ) {
472 $ret[$variant] = $this->translate( $tfirst, $variant );
475 foreach ( $tarray as $txt ) {
476 $marked = explode( $this->mMarkup
['end'], $txt, 2 );
478 foreach ( $this->mVariants
as $variant ) {
479 $ret[$variant] .= $this->mMarkup
['begin'] . $marked[0] .
480 $this->mMarkup
['end'];
481 if ( array_key_exists( 1, $marked ) ) {
482 $ret[$variant] .= $this->translate( $marked[1], $variant );
492 * Prepare manual conversion table.
495 function applyManualConv( $convRule ) {
496 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom
497 // conversion in title
498 $this->mConvRuleTitle
= $convRule->getTitle();
500 // apply manual conversion table to global table
501 $convTable = $convRule->getConvTable();
502 $action = $convRule->getRulesAction();
503 foreach ( $convTable as $variant => $pair ) {
504 if ( !$this->validateVariant( $variant ) ) {
508 if ( $action == 'add' ) {
509 foreach ( $pair as $from => $to ) {
510 // to ensure that $from and $to not be left blank
511 // so $this->translate() could always return a string
512 if ( $from ||
$to ) {
513 // more efficient than array_merge(), about 2.5 times.
514 $this->mTables
[$variant]->setPair( $from, $to );
517 } elseif ( $action == 'remove' ) {
518 $this->mTables
[$variant]->removeArray( $pair );
525 * @param string $title the title included namespace
526 * @return array of string
529 function convertNamespace( $title, $variant ) {
530 $splittitle = explode( ':', $title );
531 if ( count( $splittitle ) < 2 ) {
534 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) ) {
535 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
537 $ret = implode( ':', $splittitle );
542 * Convert a text array.
544 * @param string $tarray text array to be converted
545 * @param string $plang preferred variant
546 * @return string converted text
549 function convertArray( $tarray, $plang ) {
550 $beginlen = strlen( $this->mMarkup
['begin'] );
554 foreach ( $tarray as $text ) {
557 $text = $middle . $text;
561 // find first and last begin markup(s)
562 $firstbegin = strpos( $text, $this->mMarkup
['begin'] );
563 $lastbegin = strrpos( $text, $this->mMarkup
['begin'] );
565 // if $text contains no begin markup,
566 // append $text restore end markup to $converted
567 if( $firstbegin === false ) {
569 $converted .= $this->mMarkup
['end'];
573 // split $text into $left and $right,
574 // omit the begin markup in $right
575 $left = substr( $text, 0, $firstbegin );
576 $right = substr( $text, $lastbegin +
$beginlen );
578 // always convert $left and append it to $converted
579 // for nested case, $left is blank but can also be converted
580 $converted .= $this->autoConvert( $left, $plang );
582 // parse and apply manual rule from $right
583 $crule = new ConverterRule( $right, $this );
584 $crule->parse( $plang );
585 $right = $crule->getDisplay();
586 $this->applyManualConv( $crule );
588 // if $text contains only one begin markup,
589 // append $left and $right to $converted.
591 // otherwise it's a nested use like "-{-{}-}-",
592 // this should be handled properly.
593 if( $firstbegin === $lastbegin ) {
594 $converted .= $right;
597 // not omit the first begin markup
598 $middle = substr( $text, $firstbegin, $lastbegin - $firstbegin );
603 // Remove the last delimiter (wasn't real)
604 $converted = substr( $converted, 0, - strlen( $this->mMarkup
['end'] ) );
609 * Convert text to different variants of a language. The automatic
610 * conversion is done in autoConvert(). Here we parse the text
611 * marked with -{}-, which specifies special conversions of the
612 * text that can not be accomplished in autoConvert().
614 * Syntax of the markup:
615 * -{code1:text1;code2:text2;...}- or
616 * -{flags|code1:text1;code2:text2;...}- or
617 * -{text}- in which case no conversion should take place for text
619 * @param string $text text to be converted
620 * @return string converted text
623 function convert( $text ) {
624 global $wgDisableLangConversion;
625 if ( $wgDisableLangConversion ) return $text;
627 $plang = $this->getPreferredVariant();
629 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
630 $converted = $this->convertArray( $tarray, $plang );
636 * If a language supports multiple variants, it is
637 * possible that non-existing link in one variant
638 * actually exists in another variant. This function
639 * tries to find it. See e.g. LanguageZh.php
641 * @param string $link the name of the link
642 * @param mixed $nt the title object of the link
643 * @param boolean $ignoreOtherCond: to disable other conditions when
644 * we need to transclude a template or update a category's link
645 * @return null the input parameters may be modified upon return
648 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
649 # If the article has already existed, there is no need to
650 # check it again, otherwise it may cause a fault.
651 if ( is_object( $nt ) && $nt->exists() ) {
655 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
657 $isredir = $wgRequest->getText( 'redirect', 'yes' );
658 $action = $wgRequest->getText( 'action' );
659 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
660 $disableLinkConversion = $wgDisableLangConversion
661 ||
$wgDisableTitleConversion;
662 $linkBatch = new LinkBatch();
666 if ( $disableLinkConversion ||
667 ( !$ignoreOtherCond &&
670 ||
$action == 'submit'
671 ||
$linkconvert == 'no'
672 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
676 if ( is_object( $nt ) ) {
677 $ns = $nt->getNamespace();
680 $variants = $this->autoConvertToAllVariants( $link );
681 if ( $variants == false ) { // give up
687 foreach ( $variants as $v ) {
689 $varnt = Title
::newFromText( $v, $ns );
690 if ( !is_null( $varnt ) ) {
691 $linkBatch->addObj( $varnt );
697 // fetch all variants in single query
698 $linkBatch->execute();
700 foreach ( $titles as $varnt ) {
701 if ( $varnt->getArticleID() > 0 ) {
703 $link = $varnt->getText();
710 * Returns language specific hash options.
714 function getExtraHashOptions() {
715 $variant = $this->getPreferredVariant();
716 return '!' . $variant ;
720 * Load default conversion tables.
721 * This method must be implemented in derived class.
725 function loadDefaultTables() {
726 $name = get_class( $this );
727 wfDie( "Must implement loadDefaultTables() method in class $name" );
731 * Load conversion tables either from the cache or the disk.
734 function loadTables( $fromcache = true ) {
736 if ( $this->mTablesLoaded
) {
739 wfProfileIn( __METHOD__
);
740 $this->mTablesLoaded
= true;
741 $this->mTables
= false;
743 wfProfileIn( __METHOD__
. '-cache' );
744 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
745 wfProfileOut( __METHOD__
. '-cache' );
748 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
749 wfProfileIn( __METHOD__
. '-recache' );
750 // not in cache, or we need a fresh reload.
751 // we will first load the default tables
752 // then update them using things in MediaWiki:Zhconversiontable/*
753 $this->loadDefaultTables();
754 foreach ( $this->mVariants
as $var ) {
755 $cached = $this->parseCachedTable( $var );
756 $this->mTables
[$var]->mergeArray( $cached );
759 $this->postLoadTables();
760 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
762 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
763 wfProfileOut( __METHOD__
. '-recache' );
765 wfProfileOut( __METHOD__
);
769 * Hook for post processig after conversion tables are loaded.
772 function postLoadTables() { }
775 * Reload the conversion tables.
779 function reloadTables() {
780 if ( $this->mTables
) {
781 unset( $this->mTables
);
783 $this->mTablesLoaded
= false;
784 $this->loadTables( false );
789 * Parse the conversion table stored in the cache.
791 * The tables should be in blocks of the following form:
798 * To make the tables more manageable, subpages are allowed
799 * and will be parsed recursively if $recursive == true.
802 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
803 global $wgMessageCache;
804 static $parsed = array();
806 if ( !is_object( $wgMessageCache ) ) {
810 $key = 'Conversiontable/' . $code;
812 $key .= '/' . $subpage;
814 if ( array_key_exists( $key, $parsed ) ) {
818 if ( strpos( $code, '/' ) === false ) {
819 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
821 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
822 "Conversiontable/$code" );
823 if ( $title && $title->exists() ) {
824 $article = new Article( $title );
825 $txt = $article->getContents();
831 // get all subpage links of the form
832 // [[MediaWiki:conversiontable/zh-xx/...|...]]
833 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
835 $subs = explode( '[[', $txt );
837 foreach ( $subs as $sub ) {
838 $link = explode( ']]', $sub, 2 );
839 if ( count( $link ) != 2 ) {
842 $b = explode( '|', $link[0] );
843 $b = explode( '/', trim( $b[0] ), 3 );
844 if ( count( $b ) == 3 ) {
850 if ( $b[0] == $linkhead && $b[1] == $code ) {
851 $sublinks[] = $sublink;
856 // parse the mappings in this page
857 $blocks = explode( $this->mMarkup
['begin'], $txt );
858 array_shift( $blocks );
860 foreach ( $blocks as $block ) {
861 $mappings = explode( $this->mMarkup
['end'], $block, 2 );
862 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
864 $table = explode( ';', $stripped );
865 foreach ( $table as $t ) {
866 $m = explode( '=>', $t );
867 if ( count( $m ) != 2 )
869 // trim any trailling comments starting with '//'
870 $tt = explode( '//', $m[1], 2 );
871 $ret[trim( $m[0] )] = trim( $tt[0] );
874 $parsed[$key] = true;
877 // recursively parse the subpages
879 foreach ( $sublinks as $link ) {
880 $s = $this->parseCachedTable( $code, $link, $recursive );
881 $ret = array_merge( $ret, $s );
885 if ( $this->mUcfirst
) {
886 foreach ( $ret as $k => $v ) {
887 $ret[Language
::ucfirst( $k )] = Language
::ucfirst( $v );
894 * Enclose a string with the "no conversion" tag. This is used by
895 * various functions in the Parser.
897 * @param string $text text to be tagged for no conversion
898 * @return string the tagged text
901 function markNoConversion( $text, $noParse = false ) {
902 # don't mark if already marked
903 if ( strpos( $text, $this->mMarkup
['begin'] )
904 ||
strpos( $text, $this->mMarkup
['end'] ) ) {
908 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
913 * Convert the sorting key for category links. This should make different
914 * keys that are variants of each other map to the same key.
916 function convertCategoryKey( $key ) {
921 * Hook to refresh the cache of conversion tables when
922 * MediaWiki:conversiontable* is updated.
925 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
926 $iswatch, $section, $flags, $revision ) {
927 $titleobj = $article->getTitle();
928 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
929 $title = $titleobj->getDBkey();
930 $t = explode( '/', $title, 3 );
932 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
933 if ( $this->validateVariant( $t[1] ) ) {
934 $this->reloadTables();
942 * Armour rendered math against conversion.
943 * Wrap math into rawoutput -{R| math }- syntax.
946 function armourMath( $text ) {
947 // we need to convert '-{' and '}-' to '-{' and '}-'
948 // to avoid a unwanted '}-' appeared after the math-image.
949 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
950 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
956 * Parser for rules of language conversion , parse rules in -{ }- tag.
958 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
960 class ConverterRule
{
961 var $mText; // original text in -{text}-
962 var $mConverter; // LanguageConverter object
963 var $mManualCodeError = '<strong class="error">code error!</strong>';
964 var $mRuleDisplay = '';
965 var $mRuleTitle = false;
966 var $mRules = '';// string : the text of the rules
967 var $mRulesAction = 'none';
968 var $mFlags = array();
969 var $mConvTable = array();
970 var $mBidtable = array();// array of the translation in each variant
971 var $mUnidtable = array();// array of the translation in each variant
976 * @param string $text the text between -{ and }-
977 * @param object $converter a LanguageConverter object
980 function __construct( $text, $converter ) {
981 $this->mText
= $text;
982 $this->mConverter
= $converter;
983 foreach ( $converter->mVariants
as $v ) {
984 $this->mConvTable
[$v] = array();
989 * Check if variants array in convert array.
991 * @param string $variant Variant language code
992 * @return string Translated text
995 function getTextInBidtable( $variants ) {
996 if ( is_string( $variants ) ) {
997 $variants = array( $variants );
999 if ( !is_array( $variants ) ) {
1002 foreach ( $variants as $variant ) {
1003 if ( array_key_exists( $variant, $this->mBidtable
) ) {
1004 return $this->mBidtable
[$variant];
1011 * Parse flags with syntax -{FLAG| ... }-
1014 function parseFlags() {
1015 $text = $this->mText
;
1016 if ( strlen( $text ) < 2 ) {
1017 $this->mFlags
= array( 'R' );
1018 $this->mRules
= $text;
1023 $markup = $this->mConverter
->mMarkup
;
1024 $validFlags = $this->mConverter
->mFlags
;
1025 $variants = $this->mConverter
->mVariants
;
1027 $tt = explode( $markup['flagsep'], $text, 2 );
1028 if ( count( $tt ) == 2 ) {
1029 $f = explode( $markup['varsep'], $tt[0] );
1030 foreach ( $f as $ff ) {
1032 if ( array_key_exists( $ff, $validFlags )
1033 && !in_array( $validFlags[$ff], $flags ) ) {
1034 $flags[] = $validFlags[$ff];
1043 if ( in_array( 'R', $flags ) ) {
1044 $flags = array( 'R' );// remove other flags
1045 } elseif ( in_array( 'N', $flags ) ) {
1046 $flags = array( 'N' );// remove other flags
1047 } elseif ( in_array( '-', $flags ) ) {
1048 $flags = array( '-' );// remove other flags
1049 } elseif ( count( $flags ) == 1 && $flags[0] == 'T' ) {
1051 } elseif ( in_array( 'H', $flags ) ) {
1052 // replace A flag, and remove other flags except T
1053 $temp = array( '+', 'H' );
1054 if ( in_array( 'T', $flags ) ) {
1057 if ( in_array( 'D', $flags ) ) {
1062 if ( in_array( 'A', $flags ) ) {
1066 if ( in_array( 'D', $flags ) ) {
1067 $flags = array_diff( $flags, array( 'S' ) );
1069 $flags_temp = array();
1070 foreach ( $variants as $variant ) {
1071 // try to find flags like "zh-hans", "zh-hant"
1072 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1073 if ( in_array( $variant, $flags ) )
1074 $flags_temp[] = $variant;
1076 if ( count( $flags_temp ) !== 0 ) {
1077 $flags = $flags_temp;
1080 if ( count( $flags ) == 0 ) {
1081 $flags = array( 'S' );
1083 $this->mRules
= $rules;
1084 $this->mFlags
= $flags;
1088 * Generate conversion table.
1091 function parseRules() {
1092 $rules = $this->mRules
;
1093 $flags = $this->mFlags
;
1094 $bidtable = array();
1095 $unidtable = array();
1096 $markup = $this->mConverter
->mMarkup
;
1097 $variants = $this->mConverter
->mVariants
;
1099 // varsep_pattern for preg_split:
1100 // text should be splited by ";" only if a valid variant
1101 // name exist after the markup, for example:
1102 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1103 // <span style="font-size:120%;">yyy</span>;}-
1104 // we should split it as:
1106 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1107 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1110 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1111 foreach ( $variants as $variant ) {
1112 // zh-hans:xxx;zh-hant:yyy
1113 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|';
1114 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1115 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1116 . '\s*' . $markup['codesep'] . '|';
1118 $varsep_pattern .= '\s*$)/';
1120 $choice = preg_split( $varsep_pattern, $rules );
1122 foreach ( $choice as $c ) {
1123 $v = explode( $markup['codesep'], $c, 2 );
1124 if ( count( $v ) != 2 ) {
1125 // syntax error, skip
1128 $to = trim( $v[1] );
1130 $u = explode( $markup['unidsep'], $v, 2 );
1131 // if $to is empty, strtr() could return a wrong result
1132 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1133 $bidtable[$v] = $to;
1134 } elseif ( count( $u ) == 2 ) {
1135 $from = trim( $u[0] );
1137 if ( array_key_exists( $v, $unidtable )
1138 && !is_array( $unidtable[$v] )
1140 && in_array( $v, $variants ) ) {
1141 $unidtable[$v] = array( $from => $to );
1142 } elseif ( $to && in_array( $v, $variants ) ) {
1143 $unidtable[$v][$from] = $to;
1146 // syntax error, pass
1147 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ) {
1148 $bidtable = array();
1149 $unidtable = array();
1153 $this->mBidtable
= $bidtable;
1154 $this->mUnidtable
= $unidtable;
1160 function getRulesDesc() {
1161 $codesep = $this->mConverter
->mDescCodeSep
;
1162 $varsep = $this->mConverter
->mDescVarSep
;
1164 foreach ( $this->mBidtable
as $k => $v ) {
1165 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1167 foreach ( $this->mUnidtable
as $k => $a ) {
1168 foreach ( $a as $from => $to ) {
1169 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1170 "$codesep$to$varsep";
1177 * Parse rules conversion.
1180 function getRuleConvertedStr( $variant ) {
1181 $bidtable = $this->mBidtable
;
1182 $unidtable = $this->mUnidtable
;
1184 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1185 return $this->mRules
;
1187 // display current variant in bidirectional array
1188 $disp = $this->getTextInBidtable( $variant );
1189 // or display current variant in fallbacks
1191 $disp = $this->getTextInBidtable(
1192 $this->mConverter
->getVariantFallbacks( $variant ) );
1194 // or display current variant in unidirectional array
1195 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1196 $disp = array_values( $unidtable[$variant] );
1199 // or display frist text under disable manual convert
1201 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1202 if ( count( $bidtable ) > 0 ) {
1203 $disp = array_values( $bidtable );
1206 $disp = array_values( $unidtable );
1207 $disp = array_values( $disp[0] );
1216 * Generate conversion table for all text.
1219 function generateConvTable() {
1220 $flags = $this->mFlags
;
1221 $bidtable = $this->mBidtable
;
1222 $unidtable = $this->mUnidtable
;
1223 $manLevel = $this->mConverter
->mManualLevel
;
1226 foreach ( $this->mConverter
->mVariants
as $v ) {
1227 /* for bidirectional array
1228 fill in the missing variants, if any,
1230 if ( !array_key_exists( $v, $bidtable ) ) {
1232 $this->mConverter
->getVariantFallbacks( $v );
1233 $vf = $this->getTextInBidtable( $variantFallbacks );
1235 $bidtable[$v] = $vf;
1239 if ( array_key_exists( $v, $bidtable ) ) {
1240 foreach ( $vmarked as $vo ) {
1241 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1242 // or -{H|zh:WordZh;zh-tw:WordTw}-
1243 // or -{-|zh:WordZh;zh-tw:WordTw}-
1244 // to introduce a custom mapping between
1245 // words WordZh and WordTw in the whole text
1246 if ( $manLevel[$v] == 'bidirectional' ) {
1247 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1249 if ( $manLevel[$vo] == 'bidirectional' ) {
1250 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1255 /*for unidirectional array fill to convert tables */
1256 if ( ( $manLevel[$v] == 'bidirectional'
1257 ||
$manLevel[$v] == 'unidirectional' )
1258 && array_key_exists( $v, $unidtable ) ) {
1259 $ct = $this->mConvTable
[$v];
1260 $this->mConvTable
[$v] = array_merge( $ct, $unidtable[$v] );
1266 * Parse rules and flags.
1269 function parse( $variant = NULL ) {
1271 $variant = $this->mConverter
->getPreferredVariant();
1274 $variants = $this->mConverter
->mVariants
;
1275 $this->parseFlags();
1276 $flags = $this->mFlags
;
1278 // convert to specified variant
1279 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1280 if ( count( array_diff( $flags, $variants ) ) == 0
1281 and count( $flags ) != 0 ) {
1282 // check if current variant in flags
1283 if ( in_array( $variant, $flags ) ) {
1284 // then convert <text to convert> to current language
1285 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1287 } else { // if current variant no in flags,
1288 // then we check its fallback variants.
1290 $this->mConverter
->getVariantFallbacks( $variant );
1291 foreach ( $variantFallbacks as $variantFallback ) {
1292 // if current variant's fallback exist in flags
1293 if ( in_array( $variantFallback, $flags ) ) {
1294 // then convert <text to convert> to fallback language
1296 $this->mConverter
->autoConvert( $this->mRules
,
1302 $this->mFlags
= $flags = array( 'R' );
1305 if ( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1306 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1307 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1309 $this->parseRules();
1311 $rules = $this->mRules
;
1313 if ( count( $this->mBidtable
) == 0
1314 && count( $this->mUnidtable
) == 0 ) {
1315 if ( in_array( '+', $flags ) ||
in_array( '-', $flags ) ) {
1316 // fill all variants if text in -{A/H/-|text} without rules
1317 foreach ( $this->mConverter
->mVariants
as $v ) {
1318 $this->mBidtable
[$v] = $rules;
1320 } elseif ( !in_array( 'N', $flags ) && !in_array( 'T', $flags ) ) {
1321 $this->mFlags
= $flags = array( 'R' );
1325 if ( in_array( 'R', $flags ) ) {
1326 // if we don't do content convert, still strip the -{}- tags
1327 $this->mRuleDisplay
= $rules;
1328 } elseif ( in_array( 'N', $flags ) ) {
1329 // proces N flag: output current variant name
1330 $this->mRuleDisplay
=
1331 $this->mConverter
->mVariantNames
[ trim( $rules ) ];
1332 } elseif ( in_array( 'D', $flags ) ) {
1333 // proces D flag: output rules description
1334 $this->mRuleDisplay
= $this->getRulesDesc();
1335 } elseif ( in_array( 'H', $flags ) ||
in_array( '-', $flags ) ) {
1336 // proces H,- flag or T only: output nothing
1337 $this->mRuleDisplay
= '';
1338 } elseif ( in_array( 'S', $flags ) ) {
1339 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1341 $this->mRuleDisplay
= $this->mManualCodeError
;
1344 if ( in_array( 'T', $flags ) ) {
1345 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1348 if ( in_array( '-', $flags ) ) {
1349 $this->mRulesAction
= 'remove';
1351 if ( in_array( '+', $flags ) ) {
1352 $this->mRulesAction
= 'add';
1355 $this->generateConvTable();
1361 function hasRules() {
1366 * Get display text on markup -{...}-
1369 function getDisplay() {
1370 return $this->mRuleDisplay
;
1374 * Get converted title.
1377 function getTitle() {
1378 return $this->mRuleTitle
;
1382 * Return how deal with conversion rules.
1385 function getRulesAction() {
1386 return $this->mRulesAction
;
1390 * Get conversion table. ( bidirectional and unidirectional
1391 * conversion table )
1394 function getConvTable() {
1395 return $this->mConvTable
;
1399 * Get conversion rules string.
1402 function getRules() {
1403 return $this->mRules
;
1407 * Get conversion flags.
1410 function getFlags() {
1411 return $this->mFlags
;