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 the title produced by the conversion rule.
137 function getConvRuleTitle() {
138 return $this->mConvRuleTitle
;
142 * Get preferred language variants.
143 * @param boolean $fromUser Get it from $wgUser's preferences
144 * @param boolean $fromHeader Get it from Accept-Language
145 * @return string the preferred language code
148 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
149 global $wgDefaultLanguageVariant;
151 $req = $this->getURLVariant();
153 if ( $fromUser && !$req ) {
154 $req = $this->getUserVariant();
157 if ( $fromHeader && !$req ) {
158 $req = $this->getHeaderVariant();
161 if ( $wgDefaultLanguageVariant && !$req ) {
162 $req = $this->validateVariant( $wgDefaultLanguageVariant );
165 // This function, unlike the other get*Variant functions, is
166 // not memoized (i.e. there return value is not cached) since
167 // new information might appear during processing after this
172 return $this->mMainLanguageCode
;
176 * Validate the variant
177 * @param string $v the variant to validate
178 * @returns mixed returns the variant if it is valid, null otherwise
180 function validateVariant( $v = null ) {
181 if ( $v !== null && in_array( $v, $this->mVariants
) ) {
188 * Get the variant specified in the URL
190 * @returns mixed variant if one found, false otherwise.
192 function getURLVariant() {
196 if ( $this->mURLVariant
) {
197 return $this->mURLVariant
;
200 // see if the preference is set in the request
201 $ret = $wgRequest->getText( 'variant' );
204 $ret = $wgRequest->getVal( 'uselang' );
207 return $this->mURLVariant
= $this->validateVariant( $ret );
211 * Determine if the user has a variant set.
213 * @returns mixed variant if one found, false otherwise.
215 function getUserVariant() {
219 // memoizing this function wreaks havoc on parserTest.php
220 /* if ( $this->mUserVariant ) { */
221 /* return $this->mUserVariant; */
224 // get language variant preference from logged in users
225 // Don't call this on stub objects because that causes infinite
226 // recursion during initialisation
227 if ( $wgUser->isLoggedIn() ) {
228 $ret = $wgUser->getOption( 'variant' );
231 // figure out user lang without constructing wgLang to avoid
232 // infinite recursion
233 $ret = $wgUser->getOption( 'language' );
236 return $this->mUserVariant
= $this->validateVariant( $ret );
241 * Determine the language variant from the Accept-Language header.
243 * @returns mixed variant if one found, false otherwise.
245 function getHeaderVariant() {
249 if ( $this->mHeaderVariant
) {
250 return $this->mHeaderVariant
;
253 // see if some supported language variant is set in the
256 $acceptLanguage = $wgRequest->getHeader( 'Accept-Language' );
257 if ( !$acceptLanguage ) {
262 $result = explode( ',', strtolower( $acceptLanguage ) );
263 $languages = array();
265 foreach ( $result as $elem ) {
266 // if $elem likes 'zh-cn;q=0.9'
267 if ( ( $posi = strpos( $elem, ';' ) ) !== false ) {
268 // get the real language code likes 'zh-cn'
269 $languages[] = substr( $elem, 0, $posi );
271 $languages[] = $elem;
275 $fallback_languages = array();
276 foreach ( $languages as $language ) {
278 $language = trim( $language );
279 $this->mHeaderVariant
= $this->validateVariant( $language );
280 if ( $this->mHeaderVariant
) {
284 // To see if there are fallbacks of current language.
285 // We record these fallback variants, and process
287 $fallbacks = $this->getVariantFallbacks( $language );
288 if ( is_string( $fallbacks ) ) {
289 $fallback_languages[] = $fallbacks;
290 } elseif ( is_array( $fallbacks ) ) {
291 $fallback_languages =
292 array_merge( $fallback_languages,
297 if ( !$this->mHeaderVariant
) {
298 // process fallback languages now
299 $fallback_languages = array_unique( $fallback_languages );
300 foreach ( $fallback_languages as $language ) {
301 $this->mHeaderVariant
= $this->validateVariant( $language );
302 if ( $this->mHeaderVariant
) {
308 return $this->mHeaderVariant
;
312 * Caption convert, base on preg_replace_callback.
314 * To convert text in "title" or "alt", like '<img alt="text" ... '
315 * or '<span title="text" ... '
317 * @return string like ' alt="yyyy"' or ' title="yyyy"'
320 function captionConvert( $matches ) {
321 $toVariant = $this->getPreferredVariant();
322 $title = $matches[1];
324 // we convert captions except URL
325 if ( !strpos( $text, '://' ) ) {
326 $text = $this->translate( $text, $toVariant );
328 return " $title=\"$text\"";
332 * Dictionary-based conversion.
334 * @param string $text the text to be converted
335 * @param string $toVariant the target language code
336 * @return string the converted text
339 function autoConvert( $text, $toVariant = false ) {
340 $fname = 'LanguageConverter::autoConvert';
342 wfProfileIn( $fname );
344 if ( !$this->mTablesLoaded
) {
349 $toVariant = $this->getPreferredVariant();
355 /* we convert everything except:
356 1. html markups (anything between < and >)
358 3. place holders created by the parser
361 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
362 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
367 // this one is needed when the text is inside an html markup
368 $htmlfix = '|<[^>]+$|^[^<>]*>';
370 // disable convert to variants between <code></code> tags
371 $codefix = '<code>.+?<\/code>|';
372 // disable convertsion of <script type="text/javascript"> ... </script>
373 $scriptfix = '<script.*?>.*?<\/script>|';
374 // disable conversion of <pre xxxx> ... </pre>
375 $prefix = '<pre.*?>.*?<\/pre>|';
377 $reg = '/' . $codefix . $scriptfix . $prefix .
378 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
380 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
382 $m = array_shift( $matches );
384 $ret = $this->translate( $m[0], $toVariant );
385 $mstart = $m[1] +
strlen( $m[0] );
387 // enable convertsion of '<img alt="xxxx" ... '
388 // or '<span title="xxxx" ... '
389 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
394 foreach ( $matches as $m ) {
395 $mark = substr( $text, $mstart, $m[1] - $mstart );
396 $mark = preg_replace_callback( $captionpattern,
397 array( &$this, 'captionConvert' ),
399 // Let's convert the trtext only once,
400 // it would give us more performance improvement
402 $trtext .= $m[0] . $trtextmark;
403 $mstart = $m[1] +
strlen( $m[0] );
406 $trtext = $this->translate( $trtext, $toVariant );
407 $trtext = StringUtils
::explode( $trtextmark, $trtext );
408 foreach ( $trtext as $t ) {
409 $ret .= array_shift( $notrtext );
412 wfProfileOut( $fname );
417 * Translate a string to a variant.
418 * Doesn't process markup or do any of that other stuff, for that use
421 * @param string $text Text to convert
422 * @param string $variant Variant language code
423 * @return string Translated text
426 function translate( $text, $variant ) {
427 wfProfileIn( __METHOD__
);
428 // If $text is empty or only includes spaces, do nothing
429 // Otherwise translate it
430 if ( trim( $text ) ) {
431 if ( !$this->mTablesLoaded
) {
434 $text = $this->mTables
[$variant]->replace( $text );
436 wfProfileOut( __METHOD__
);
441 * Convert text to all supported variants.
443 * @param string $text the text to be converted
444 * @return array of string
447 function autoConvertToAllVariants( $text ) {
448 $fname = 'LanguageConverter::autoConvertToAllVariants';
449 wfProfileIn( $fname );
450 if ( !$this->mTablesLoaded
) {
455 foreach ( $this->mVariants
as $variant ) {
456 $ret[$variant] = $this->translate( $text, $variant );
459 wfProfileOut( $fname );
464 * Convert link text to all supported variants.
466 * @param string $text the text to be converted
467 * @return array of string
470 function convertLinkToAllVariants( $text ) {
471 if ( !$this->mTablesLoaded
) {
476 $tarray = explode( $this->mMarkup
['begin'], $text );
477 $tfirst = array_shift( $tarray );
479 foreach ( $this->mVariants
as $variant ) {
480 $ret[$variant] = $this->translate( $tfirst, $variant );
483 foreach ( $tarray as $txt ) {
484 $marked = explode( $this->mMarkup
['end'], $txt, 2 );
486 foreach ( $this->mVariants
as $variant ) {
487 $ret[$variant] .= $this->mMarkup
['begin'] . $marked[0] .
488 $this->mMarkup
['end'];
489 if ( array_key_exists( 1, $marked ) ) {
490 $ret[$variant] .= $this->translate( $marked[1], $variant );
500 * Prepare manual conversion table.
503 function applyManualConv( $convRule ) {
504 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom
505 // conversion in title
506 $this->mConvRuleTitle
= $convRule->getTitle();
508 // apply manual conversion table to global table
509 $convTable = $convRule->getConvTable();
510 $action = $convRule->getRulesAction();
511 foreach ( $convTable as $variant => $pair ) {
512 if ( !$this->validateVariant( $variant ) ) {
516 if ( $action == 'add' ) {
517 foreach ( $pair as $from => $to ) {
518 // to ensure that $from and $to not be left blank
519 // so $this->translate() could always return a string
520 if ( $from ||
$to ) {
521 // more efficient than array_merge(), about 2.5 times.
522 $this->mTables
[$variant]->setPair( $from, $to );
525 } elseif ( $action == 'remove' ) {
526 $this->mTables
[$variant]->removeArray( $pair );
533 * @param string $title the title included namespace
534 * @return array of string
537 function convertNamespace( $title, $variant ) {
538 $splittitle = explode( ':', $title );
539 if ( count( $splittitle ) < 2 ) {
542 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) ) {
543 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
545 $ret = implode( ':', $splittitle );
550 * Convert a text array.
552 * @param string $tarray text array to be converted
553 * @param string $plang preferred variant
554 * @return string converted text
557 function convertArray( $tarray, $plang ) {
558 $beginlen = strlen( $this->mMarkup
['begin'] );
562 foreach ( $tarray as $text ) {
565 $text = $middle . $text;
569 // find first and last begin markup(s)
570 $firstbegin = strpos( $text, $this->mMarkup
['begin'] );
571 $lastbegin = strrpos( $text, $this->mMarkup
['begin'] );
573 // if $text contains no begin markup,
574 // append $text to $converted and restore end markup
575 if( $firstbegin === false ) {
576 $converted .= $this->autoConvert( $text, $plang );
577 $converted .= $this->mMarkup
['end'];
581 // split $text into $left and $right,
582 // omit the begin markup in $right
583 $left = substr( $text, 0, $firstbegin );
584 $right = substr( $text, $lastbegin +
$beginlen );
586 // always convert $left and append it to $converted
587 // for nested case, $left is blank but can also be converted
588 $converted .= $this->autoConvert( $left, $plang );
590 // parse and apply manual rule from $right
591 $crule = new ConverterRule( $right, $this );
592 $crule->parse( $plang );
593 $right = $crule->getDisplay();
594 $this->applyManualConv( $crule );
596 // if $text contains only one begin markup,
597 // append $left and $right to $converted.
599 // otherwise it's a nested use like "-{-{}-}-",
600 // this should be handled properly.
601 if( $firstbegin === $lastbegin ) {
602 $converted .= $right;
605 // not omit the first begin markup
606 $middle = substr( $text, $firstbegin, $lastbegin - $firstbegin );
611 // Remove the last delimiter (wasn't real)
612 $converted = substr( $converted, 0, - strlen( $this->mMarkup
['end'] ) );
617 * Convert text to different variants of a language. The automatic
618 * conversion is done in autoConvert(). Here we parse the text
619 * marked with -{}-, which specifies special conversions of the
620 * text that can not be accomplished in autoConvert().
622 * Syntax of the markup:
623 * -{code1:text1;code2:text2;...}- or
624 * -{flags|code1:text1;code2:text2;...}- or
625 * -{text}- in which case no conversion should take place for text
627 * @param string $text text to be converted
628 * @return string converted text
631 function convert( $text ) {
632 global $wgDisableLangConversion;
633 if ( $wgDisableLangConversion ) return $text;
635 $plang = $this->getPreferredVariant();
637 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
638 $converted = $this->convertArray( $tarray, $plang );
644 * If a language supports multiple variants, it is
645 * possible that non-existing link in one variant
646 * actually exists in another variant. This function
647 * tries to find it. See e.g. LanguageZh.php
649 * @param string $link the name of the link
650 * @param mixed $nt the title object of the link
651 * @param boolean $ignoreOtherCond: to disable other conditions when
652 * we need to transclude a template or update a category's link
653 * @return null the input parameters may be modified upon return
656 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
657 # If the article has already existed, there is no need to
658 # check it again, otherwise it may cause a fault.
659 if ( is_object( $nt ) && $nt->exists() ) {
663 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
665 $isredir = $wgRequest->getText( 'redirect', 'yes' );
666 $action = $wgRequest->getText( 'action' );
667 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
668 $disableLinkConversion = $wgDisableLangConversion
669 ||
$wgDisableTitleConversion;
670 $linkBatch = new LinkBatch();
674 if ( $disableLinkConversion ||
675 ( !$ignoreOtherCond &&
678 ||
$action == 'submit'
679 ||
$linkconvert == 'no'
680 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
684 if ( is_object( $nt ) ) {
685 $ns = $nt->getNamespace();
688 $variants = $this->autoConvertToAllVariants( $link );
689 if ( $variants == false ) { // give up
695 foreach ( $variants as $v ) {
697 $varnt = Title
::newFromText( $v, $ns );
698 if ( !is_null( $varnt ) ) {
699 $linkBatch->addObj( $varnt );
705 // fetch all variants in single query
706 $linkBatch->execute();
708 foreach ( $titles as $varnt ) {
709 if ( $varnt->getArticleID() > 0 ) {
711 $link = $varnt->getText();
718 * Returns language specific hash options.
722 function getExtraHashOptions() {
723 $variant = $this->getPreferredVariant();
724 return '!' . $variant ;
728 * Load default conversion tables.
729 * This method must be implemented in derived class.
733 function loadDefaultTables() {
734 $name = get_class( $this );
735 wfDie( "Must implement loadDefaultTables() method in class $name" );
739 * Load conversion tables either from the cache or the disk.
742 function loadTables( $fromcache = true ) {
744 if ( $this->mTablesLoaded
) {
747 wfProfileIn( __METHOD__
);
748 $this->mTablesLoaded
= true;
749 $this->mTables
= false;
751 wfProfileIn( __METHOD__
. '-cache' );
752 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
753 wfProfileOut( __METHOD__
. '-cache' );
756 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
757 wfProfileIn( __METHOD__
. '-recache' );
758 // not in cache, or we need a fresh reload.
759 // we will first load the default tables
760 // then update them using things in MediaWiki:Zhconversiontable/*
761 $this->loadDefaultTables();
762 foreach ( $this->mVariants
as $var ) {
763 $cached = $this->parseCachedTable( $var );
764 $this->mTables
[$var]->mergeArray( $cached );
767 $this->postLoadTables();
768 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
770 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
771 wfProfileOut( __METHOD__
. '-recache' );
773 wfProfileOut( __METHOD__
);
777 * Hook for post processig after conversion tables are loaded.
780 function postLoadTables() { }
783 * Reload the conversion tables.
787 function reloadTables() {
788 if ( $this->mTables
) {
789 unset( $this->mTables
);
791 $this->mTablesLoaded
= false;
792 $this->loadTables( false );
797 * Parse the conversion table stored in the cache.
799 * The tables should be in blocks of the following form:
806 * To make the tables more manageable, subpages are allowed
807 * and will be parsed recursively if $recursive == true.
810 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
811 global $wgMessageCache;
812 static $parsed = array();
814 if ( !is_object( $wgMessageCache ) ) {
818 $key = 'Conversiontable/' . $code;
820 $key .= '/' . $subpage;
822 if ( array_key_exists( $key, $parsed ) ) {
826 if ( strpos( $code, '/' ) === false ) {
827 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
829 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
830 "Conversiontable/$code" );
831 if ( $title && $title->exists() ) {
832 $article = new Article( $title );
833 $txt = $article->getContents();
839 // get all subpage links of the form
840 // [[MediaWiki:conversiontable/zh-xx/...|...]]
841 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
843 $subs = explode( '[[', $txt );
845 foreach ( $subs as $sub ) {
846 $link = explode( ']]', $sub, 2 );
847 if ( count( $link ) != 2 ) {
850 $b = explode( '|', $link[0] );
851 $b = explode( '/', trim( $b[0] ), 3 );
852 if ( count( $b ) == 3 ) {
858 if ( $b[0] == $linkhead && $b[1] == $code ) {
859 $sublinks[] = $sublink;
864 // parse the mappings in this page
865 $blocks = explode( $this->mMarkup
['begin'], $txt );
866 array_shift( $blocks );
868 foreach ( $blocks as $block ) {
869 $mappings = explode( $this->mMarkup
['end'], $block, 2 );
870 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
872 $table = explode( ';', $stripped );
873 foreach ( $table as $t ) {
874 $m = explode( '=>', $t );
875 if ( count( $m ) != 2 )
877 // trim any trailling comments starting with '//'
878 $tt = explode( '//', $m[1], 2 );
879 $ret[trim( $m[0] )] = trim( $tt[0] );
882 $parsed[$key] = true;
885 // recursively parse the subpages
887 foreach ( $sublinks as $link ) {
888 $s = $this->parseCachedTable( $code, $link, $recursive );
889 $ret = array_merge( $ret, $s );
893 if ( $this->mUcfirst
) {
894 foreach ( $ret as $k => $v ) {
895 $ret[Language
::ucfirst( $k )] = Language
::ucfirst( $v );
902 * Enclose a string with the "no conversion" tag. This is used by
903 * various functions in the Parser.
905 * @param string $text text to be tagged for no conversion
906 * @return string the tagged text
909 function markNoConversion( $text, $noParse = false ) {
910 # don't mark if already marked
911 if ( strpos( $text, $this->mMarkup
['begin'] )
912 ||
strpos( $text, $this->mMarkup
['end'] ) ) {
916 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
921 * Convert the sorting key for category links. This should make different
922 * keys that are variants of each other map to the same key.
924 function convertCategoryKey( $key ) {
929 * Hook to refresh the cache of conversion tables when
930 * MediaWiki:conversiontable* is updated.
933 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
934 $iswatch, $section, $flags, $revision ) {
935 $titleobj = $article->getTitle();
936 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
937 $title = $titleobj->getDBkey();
938 $t = explode( '/', $title, 3 );
940 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
941 if ( $this->validateVariant( $t[1] ) ) {
942 $this->reloadTables();
950 * Armour rendered math against conversion.
951 * Wrap math into rawoutput -{R| math }- syntax.
954 function armourMath( $text ) {
955 // we need to convert '-{' and '}-' to '-{' and '}-'
956 // to avoid a unwanted '}-' appeared after the math-image.
957 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
958 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
964 * Parser for rules of language conversion , parse rules in -{ }- tag.
966 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
968 class ConverterRule
{
969 var $mText; // original text in -{text}-
970 var $mConverter; // LanguageConverter object
971 var $mManualCodeError = '<strong class="error">code error!</strong>';
972 var $mRuleDisplay = '';
973 var $mRuleTitle = false;
974 var $mRules = '';// string : the text of the rules
975 var $mRulesAction = 'none';
976 var $mFlags = array();
977 var $mConvTable = array();
978 var $mBidtable = array();// array of the translation in each variant
979 var $mUnidtable = array();// array of the translation in each variant
984 * @param string $text the text between -{ and }-
985 * @param object $converter a LanguageConverter object
988 function __construct( $text, $converter ) {
989 $this->mText
= $text;
990 $this->mConverter
= $converter;
991 foreach ( $converter->mVariants
as $v ) {
992 $this->mConvTable
[$v] = array();
997 * Check if variants array in convert array.
999 * @param string $variant Variant language code
1000 * @return string Translated text
1003 function getTextInBidtable( $variants ) {
1004 if ( is_string( $variants ) ) {
1005 $variants = array( $variants );
1007 if ( !is_array( $variants ) ) {
1010 foreach ( $variants as $variant ) {
1011 if ( array_key_exists( $variant, $this->mBidtable
) ) {
1012 return $this->mBidtable
[$variant];
1019 * Parse flags with syntax -{FLAG| ... }-
1022 function parseFlags() {
1023 $text = $this->mText
;
1024 if ( strlen( $text ) < 2 ) {
1025 $this->mFlags
= array( 'R' );
1026 $this->mRules
= $text;
1031 $markup = $this->mConverter
->mMarkup
;
1032 $validFlags = $this->mConverter
->mFlags
;
1033 $variants = $this->mConverter
->mVariants
;
1035 $tt = explode( $markup['flagsep'], $text, 2 );
1036 if ( count( $tt ) == 2 ) {
1037 $f = explode( $markup['varsep'], $tt[0] );
1038 foreach ( $f as $ff ) {
1040 if ( array_key_exists( $ff, $validFlags )
1041 && !in_array( $validFlags[$ff], $flags ) ) {
1042 $flags[] = $validFlags[$ff];
1051 if ( in_array( 'R', $flags ) ) {
1052 $flags = array( 'R' );// remove other flags
1053 } elseif ( in_array( 'N', $flags ) ) {
1054 $flags = array( 'N' );// remove other flags
1055 } elseif ( in_array( '-', $flags ) ) {
1056 $flags = array( '-' );// remove other flags
1057 } elseif ( count( $flags ) == 1 && $flags[0] == 'T' ) {
1059 } elseif ( in_array( 'H', $flags ) ) {
1060 // replace A flag, and remove other flags except T
1061 $temp = array( '+', 'H' );
1062 if ( in_array( 'T', $flags ) ) {
1065 if ( in_array( 'D', $flags ) ) {
1070 if ( in_array( 'A', $flags ) ) {
1074 if ( in_array( 'D', $flags ) ) {
1075 $flags = array_diff( $flags, array( 'S' ) );
1077 $flags_temp = array();
1078 foreach ( $variants as $variant ) {
1079 // try to find flags like "zh-hans", "zh-hant"
1080 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1081 if ( in_array( $variant, $flags ) )
1082 $flags_temp[] = $variant;
1084 if ( count( $flags_temp ) !== 0 ) {
1085 $flags = $flags_temp;
1088 if ( count( $flags ) == 0 ) {
1089 $flags = array( 'S' );
1091 $this->mRules
= $rules;
1092 $this->mFlags
= $flags;
1096 * Generate conversion table.
1099 function parseRules() {
1100 $rules = $this->mRules
;
1101 $flags = $this->mFlags
;
1102 $bidtable = array();
1103 $unidtable = array();
1104 $markup = $this->mConverter
->mMarkup
;
1105 $variants = $this->mConverter
->mVariants
;
1107 // varsep_pattern for preg_split:
1108 // text should be splited by ";" only if a valid variant
1109 // name exist after the markup, for example:
1110 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1111 // <span style="font-size:120%;">yyy</span>;}-
1112 // we should split it as:
1114 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1115 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1118 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1119 foreach ( $variants as $variant ) {
1120 // zh-hans:xxx;zh-hant:yyy
1121 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|';
1122 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1123 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1124 . '\s*' . $markup['codesep'] . '|';
1126 $varsep_pattern .= '\s*$)/';
1128 $choice = preg_split( $varsep_pattern, $rules );
1130 foreach ( $choice as $c ) {
1131 $v = explode( $markup['codesep'], $c, 2 );
1132 if ( count( $v ) != 2 ) {
1133 // syntax error, skip
1136 $to = trim( $v[1] );
1138 $u = explode( $markup['unidsep'], $v, 2 );
1139 // if $to is empty, strtr() could return a wrong result
1140 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1141 $bidtable[$v] = $to;
1142 } elseif ( count( $u ) == 2 ) {
1143 $from = trim( $u[0] );
1145 if ( array_key_exists( $v, $unidtable )
1146 && !is_array( $unidtable[$v] )
1148 && in_array( $v, $variants ) ) {
1149 $unidtable[$v] = array( $from => $to );
1150 } elseif ( $to && in_array( $v, $variants ) ) {
1151 $unidtable[$v][$from] = $to;
1154 // syntax error, pass
1155 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ) {
1156 $bidtable = array();
1157 $unidtable = array();
1161 $this->mBidtable
= $bidtable;
1162 $this->mUnidtable
= $unidtable;
1168 function getRulesDesc() {
1169 $codesep = $this->mConverter
->mDescCodeSep
;
1170 $varsep = $this->mConverter
->mDescVarSep
;
1172 foreach ( $this->mBidtable
as $k => $v ) {
1173 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1175 foreach ( $this->mUnidtable
as $k => $a ) {
1176 foreach ( $a as $from => $to ) {
1177 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1178 "$codesep$to$varsep";
1185 * Parse rules conversion.
1188 function getRuleConvertedStr( $variant ) {
1189 $bidtable = $this->mBidtable
;
1190 $unidtable = $this->mUnidtable
;
1192 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1193 return $this->mRules
;
1195 // display current variant in bidirectional array
1196 $disp = $this->getTextInBidtable( $variant );
1197 // or display current variant in fallbacks
1199 $disp = $this->getTextInBidtable(
1200 $this->mConverter
->getVariantFallbacks( $variant ) );
1202 // or display current variant in unidirectional array
1203 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1204 $disp = array_values( $unidtable[$variant] );
1207 // or display frist text under disable manual convert
1209 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1210 if ( count( $bidtable ) > 0 ) {
1211 $disp = array_values( $bidtable );
1214 $disp = array_values( $unidtable );
1215 $disp = array_values( $disp[0] );
1224 * Generate conversion table for all text.
1227 function generateConvTable() {
1228 $flags = $this->mFlags
;
1229 $bidtable = $this->mBidtable
;
1230 $unidtable = $this->mUnidtable
;
1231 $manLevel = $this->mConverter
->mManualLevel
;
1234 foreach ( $this->mConverter
->mVariants
as $v ) {
1235 /* for bidirectional array
1236 fill in the missing variants, if any,
1238 if ( !array_key_exists( $v, $bidtable ) ) {
1240 $this->mConverter
->getVariantFallbacks( $v );
1241 $vf = $this->getTextInBidtable( $variantFallbacks );
1243 $bidtable[$v] = $vf;
1247 if ( array_key_exists( $v, $bidtable ) ) {
1248 foreach ( $vmarked as $vo ) {
1249 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1250 // or -{H|zh:WordZh;zh-tw:WordTw}-
1251 // or -{-|zh:WordZh;zh-tw:WordTw}-
1252 // to introduce a custom mapping between
1253 // words WordZh and WordTw in the whole text
1254 if ( $manLevel[$v] == 'bidirectional' ) {
1255 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1257 if ( $manLevel[$vo] == 'bidirectional' ) {
1258 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1263 /*for unidirectional array fill to convert tables */
1264 if ( ( $manLevel[$v] == 'bidirectional'
1265 ||
$manLevel[$v] == 'unidirectional' )
1266 && array_key_exists( $v, $unidtable ) ) {
1267 $ct = $this->mConvTable
[$v];
1268 $this->mConvTable
[$v] = array_merge( $ct, $unidtable[$v] );
1274 * Parse rules and flags.
1277 function parse( $variant = NULL ) {
1279 $variant = $this->mConverter
->getPreferredVariant();
1282 $variants = $this->mConverter
->mVariants
;
1283 $this->parseFlags();
1284 $flags = $this->mFlags
;
1286 // convert to specified variant
1287 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1288 if ( count( array_diff( $flags, $variants ) ) == 0
1289 and count( $flags ) != 0 ) {
1290 // check if current variant in flags
1291 if ( in_array( $variant, $flags ) ) {
1292 // then convert <text to convert> to current language
1293 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1295 } else { // if current variant no in flags,
1296 // then we check its fallback variants.
1298 $this->mConverter
->getVariantFallbacks( $variant );
1299 foreach ( $variantFallbacks as $variantFallback ) {
1300 // if current variant's fallback exist in flags
1301 if ( in_array( $variantFallback, $flags ) ) {
1302 // then convert <text to convert> to fallback language
1304 $this->mConverter
->autoConvert( $this->mRules
,
1310 $this->mFlags
= $flags = array( 'R' );
1313 if ( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1314 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1315 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1317 $this->parseRules();
1319 $rules = $this->mRules
;
1321 if ( count( $this->mBidtable
) == 0
1322 && count( $this->mUnidtable
) == 0 ) {
1323 if ( in_array( '+', $flags ) ||
in_array( '-', $flags ) ) {
1324 // fill all variants if text in -{A/H/-|text} without rules
1325 foreach ( $this->mConverter
->mVariants
as $v ) {
1326 $this->mBidtable
[$v] = $rules;
1328 } elseif ( !in_array( 'N', $flags ) && !in_array( 'T', $flags ) ) {
1329 $this->mFlags
= $flags = array( 'R' );
1333 if ( in_array( 'R', $flags ) ) {
1334 // if we don't do content convert, still strip the -{}- tags
1335 $this->mRuleDisplay
= $rules;
1336 } elseif ( in_array( 'N', $flags ) ) {
1337 // proces N flag: output current variant name
1338 $this->mRuleDisplay
=
1339 $this->mConverter
->mVariantNames
[ trim( $rules ) ];
1340 } elseif ( in_array( 'D', $flags ) ) {
1341 // proces D flag: output rules description
1342 $this->mRuleDisplay
= $this->getRulesDesc();
1343 } elseif ( in_array( 'H', $flags ) ||
in_array( '-', $flags ) ) {
1344 // proces H,- flag or T only: output nothing
1345 $this->mRuleDisplay
= '';
1346 } elseif ( in_array( 'S', $flags ) ) {
1347 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1349 $this->mRuleDisplay
= $this->mManualCodeError
;
1352 if ( in_array( 'T', $flags ) ) {
1353 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1356 if ( in_array( '-', $flags ) ) {
1357 $this->mRulesAction
= 'remove';
1359 if ( in_array( '+', $flags ) ) {
1360 $this->mRulesAction
= 'add';
1363 $this->generateConvTable();
1369 function hasRules() {
1374 * Get display text on markup -{...}-
1377 function getDisplay() {
1378 return $this->mRuleDisplay
;
1382 * Get converted title.
1385 function getTitle() {
1386 return $this->mRuleTitle
;
1390 * Return how deal with conversion rules.
1393 function getRulesAction() {
1394 return $this->mRulesAction
;
1398 * Get conversion table. ( bidirectional and unidirectional
1399 * conversion table )
1402 function getConvTable() {
1403 return $this->mConvTable
;
1407 * Get conversion rules string.
1410 function getRules() {
1411 return $this->mRules
;
1415 * Get conversion flags.
1418 function getFlags() {
1419 return $this->mFlags
;