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 ( isset( $this->mVariantFallbacks
[$v] ) ) {
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 && !isset( $req ) ) {
146 $req = $this->getUserVariant();
149 if ( $fromHeader && !isset( $req ) ) {
150 $req = $this->getHeaderVariant();
153 if ( $wgDefaultLanguageVariant && !isset( $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
161 if ( isset( $req ) ) {
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 ( isset( $v ) && 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' );
195 if ( !isset( $ret ) ) {
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 ) { // not using isset because getHeader returns false
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 ( isset( $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 ( !isset( $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 ( isset( $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 fragment.
544 * @param string $text text to be converted
545 * @param string $plang preferred variant
546 * @return string converted text
549 function convertFragment( $text, $plang ) {
550 $marked = explode( $this->mMarkup
['begin'], $text, 2 );
553 $converted .= $this->autoConvert( $marked[0], $plang );
555 if ( array_key_exists( 1, $marked ) ) {
556 $crule = new ConverterRule( $marked[1], $this );
557 $crule->parse( $plang );
558 $converted .= $crule->getDisplay();
559 $this->applyManualConv( $crule );
561 $converted .= $this->mMarkup
['end'];
568 * Convert text to different variants of a language. The automatic
569 * conversion is done in autoConvert(). Here we parse the text
570 * marked with -{}-, which specifies special conversions of the
571 * text that can not be accomplished in autoConvert().
573 * Syntax of the markup:
574 * -{code1:text1;code2:text2;...}- or
575 * -{flags|code1:text1;code2:text2;...}- or
576 * -{text}- in which case no conversion should take place for text
578 * @param string $text text to be converted
579 * @return string converted text
582 function convert( $text ) {
583 global $wgDisableLangConversion;
584 if ( $wgDisableLangConversion ) return $text;
586 $plang = $this->getPreferredVariant();
588 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
591 foreach ( $tarray as $txt ) {
592 $converted .= $this->convertFragment( $txt, $plang );
595 // Remove the last delimiter (wasn't real)
596 $converted = substr( $converted, 0, - strlen( $this->mMarkup
['end'] ) );
601 * If a language supports multiple variants, it is
602 * possible that non-existing link in one variant
603 * actually exists in another variant. This function
604 * tries to find it. See e.g. LanguageZh.php
606 * @param string $link the name of the link
607 * @param mixed $nt the title object of the link
608 * @param boolean $ignoreOtherCond: to disable other conditions when
609 * we need to transclude a template or update a category's link
610 * @return null the input parameters may be modified upon return
613 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
614 # If the article has already existed, there is no need to
615 # check it again, otherwise it may cause a fault.
616 if ( is_object( $nt ) && $nt->exists() ) {
620 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
622 $isredir = $wgRequest->getText( 'redirect', 'yes' );
623 $action = $wgRequest->getText( 'action' );
624 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
625 $disableLinkConversion = $wgDisableLangConversion
626 ||
$wgDisableTitleConversion;
627 $linkBatch = new LinkBatch();
631 if ( $disableLinkConversion ||
632 ( !$ignoreOtherCond &&
635 ||
$action == 'submit'
636 ||
$linkconvert == 'no'
637 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
641 if ( is_object( $nt ) ) {
642 $ns = $nt->getNamespace();
645 $variants = $this->autoConvertToAllVariants( $link );
646 if ( $variants == false ) { // give up
652 foreach ( $variants as $v ) {
654 $varnt = Title
::newFromText( $v, $ns );
655 if ( !is_null( $varnt ) ) {
656 $linkBatch->addObj( $varnt );
662 // fetch all variants in single query
663 $linkBatch->execute();
665 foreach ( $titles as $varnt ) {
666 if ( $varnt->getArticleID() > 0 ) {
668 $link = $varnt->getText();
675 * Returns language specific hash options.
679 function getExtraHashOptions() {
680 $variant = $this->getPreferredVariant();
681 return '!' . $variant ;
685 * Load default conversion tables.
686 * This method must be implemented in derived class.
690 function loadDefaultTables() {
691 $name = get_class( $this );
692 wfDie( "Must implement loadDefaultTables() method in class $name" );
696 * Load conversion tables either from the cache or the disk.
699 function loadTables( $fromcache = true ) {
701 if ( $this->mTablesLoaded
) {
704 wfProfileIn( __METHOD__
);
705 $this->mTablesLoaded
= true;
706 $this->mTables
= false;
708 wfProfileIn( __METHOD__
. '-cache' );
709 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
710 wfProfileOut( __METHOD__
. '-cache' );
713 ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
714 wfProfileIn( __METHOD__
. '-recache' );
715 // not in cache, or we need a fresh reload.
716 // we will first load the default tables
717 // then update them using things in MediaWiki:Zhconversiontable/*
718 $this->loadDefaultTables();
719 foreach ( $this->mVariants
as $var ) {
720 $cached = $this->parseCachedTable( $var );
721 $this->mTables
[$var]->mergeArray( $cached );
724 $this->postLoadTables();
725 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
727 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
728 wfProfileOut( __METHOD__
. '-recache' );
730 wfProfileOut( __METHOD__
);
734 * Hook for post processig after conversion tables are loaded.
737 function postLoadTables() { }
740 * Reload the conversion tables.
744 function reloadTables() {
745 if ( $this->mTables
) {
746 unset( $this->mTables
);
748 $this->mTablesLoaded
= false;
749 $this->loadTables( false );
754 * Parse the conversion table stored in the cache.
756 * The tables should be in blocks of the following form:
763 * To make the tables more manageable, subpages are allowed
764 * and will be parsed recursively if $recursive == true.
767 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
768 global $wgMessageCache;
769 static $parsed = array();
771 if ( !is_object( $wgMessageCache ) ) {
775 $key = 'Conversiontable/' . $code;
777 $key .= '/' . $subpage;
779 if ( array_key_exists( $key, $parsed ) ) {
783 if ( strpos( $code, '/' ) === false ) {
784 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
786 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
787 "Conversiontable/$code" );
788 if ( $title && $title->exists() ) {
789 $article = new Article( $title );
790 $txt = $article->getContents();
796 // get all subpage links of the form
797 // [[MediaWiki:conversiontable/zh-xx/...|...]]
798 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
800 $subs = explode( '[[', $txt );
802 foreach ( $subs as $sub ) {
803 $link = explode( ']]', $sub, 2 );
804 if ( count( $link ) != 2 ) {
807 $b = explode( '|', $link[0] );
808 $b = explode( '/', trim( $b[0] ), 3 );
809 if ( count( $b ) == 3 ) {
815 if ( $b[0] == $linkhead && $b[1] == $code ) {
816 $sublinks[] = $sublink;
821 // parse the mappings in this page
822 $blocks = explode( $this->mMarkup
['begin'], $txt );
823 array_shift( $blocks );
825 foreach ( $blocks as $block ) {
826 $mappings = explode( $this->mMarkup
['end'], $block, 2 );
827 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
829 $table = explode( ';', $stripped );
830 foreach ( $table as $t ) {
831 $m = explode( '=>', $t );
832 if ( count( $m ) != 2 )
834 // trim any trailling comments starting with '//'
835 $tt = explode( '//', $m[1], 2 );
836 $ret[trim( $m[0] )] = trim( $tt[0] );
839 $parsed[$key] = true;
842 // recursively parse the subpages
844 foreach ( $sublinks as $link ) {
845 $s = $this->parseCachedTable( $code, $link, $recursive );
846 $ret = array_merge( $ret, $s );
850 if ( $this->mUcfirst
) {
851 foreach ( $ret as $k => $v ) {
852 $ret[Language
::ucfirst( $k )] = Language
::ucfirst( $v );
859 * Enclose a string with the "no conversion" tag. This is used by
860 * various functions in the Parser.
862 * @param string $text text to be tagged for no conversion
863 * @return string the tagged text
866 function markNoConversion( $text, $noParse = false ) {
867 # don't mark if already marked
868 if ( strpos( $text, $this->mMarkup
['begin'] )
869 ||
strpos( $text, $this->mMarkup
['end'] ) ) {
873 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
878 * Convert the sorting key for category links. This should make different
879 * keys that are variants of each other map to the same key.
881 function convertCategoryKey( $key ) {
886 * Hook to refresh the cache of conversion tables when
887 * MediaWiki:conversiontable* is updated.
890 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
891 $iswatch, $section, $flags, $revision ) {
892 $titleobj = $article->getTitle();
893 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
894 $title = $titleobj->getDBkey();
895 $t = explode( '/', $title, 3 );
897 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
898 if ( $this->validateVariant( $t[1] ) ) {
899 $this->reloadTables();
907 * Armour rendered math against conversion.
908 * Wrap math into rawoutput -{R| math }- syntax.
911 function armourMath( $text ) {
912 // we need to convert '-{' and '}-' to '-{' and '}-'
913 // to avoid a unwanted '}-' appeared after the math-image.
914 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
915 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
921 * Parser for rules of language conversion , parse rules in -{ }- tag.
923 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
925 class ConverterRule
{
926 var $mText; // original text in -{text}-
927 var $mConverter; // LanguageConverter object
928 var $mManualCodeError = '<strong class="error">code error!</strong>';
929 var $mRuleDisplay = '';
930 var $mRuleTitle = false;
931 var $mRules = '';// string : the text of the rules
932 var $mRulesAction = 'none';
933 var $mFlags = array();
934 var $mConvTable = array();
935 var $mBidtable = array();// array of the translation in each variant
936 var $mUnidtable = array();// array of the translation in each variant
941 * @param string $text the text between -{ and }-
942 * @param object $converter a LanguageConverter object
945 function __construct( $text, $converter ) {
946 $this->mText
= $text;
947 $this->mConverter
= $converter;
948 foreach ( $converter->mVariants
as $v ) {
949 $this->mConvTable
[$v] = array();
954 * Check if variants array in convert array.
956 * @param string $variant Variant language code
957 * @return string Translated text
960 function getTextInBidtable( $variants ) {
961 if ( is_string( $variants ) ) {
962 $variants = array( $variants );
964 if ( !is_array( $variants ) ) {
967 foreach ( $variants as $variant ) {
968 if ( array_key_exists( $variant, $this->mBidtable
) ) {
969 return $this->mBidtable
[$variant];
976 * Parse flags with syntax -{FLAG| ... }-
979 function parseFlags() {
980 $text = $this->mText
;
981 if ( strlen( $text ) < 2 ) {
982 $this->mFlags
= array( 'R' );
983 $this->mRules
= $text;
988 $markup = $this->mConverter
->mMarkup
;
989 $validFlags = $this->mConverter
->mFlags
;
990 $variants = $this->mConverter
->mVariants
;
992 $tt = explode( $markup['flagsep'], $text, 2 );
993 if ( count( $tt ) == 2 ) {
994 $f = explode( $markup['varsep'], $tt[0] );
995 foreach ( $f as $ff ) {
997 if ( array_key_exists( $ff, $validFlags )
998 && !in_array( $validFlags[$ff], $flags ) ) {
999 $flags[] = $validFlags[$ff];
1008 if ( in_array( 'R', $flags ) ) {
1009 $flags = array( 'R' );// remove other flags
1010 } elseif ( in_array( 'N', $flags ) ) {
1011 $flags = array( 'N' );// remove other flags
1012 } elseif ( in_array( '-', $flags ) ) {
1013 $flags = array( '-' );// remove other flags
1014 } elseif ( count( $flags ) == 1 && $flags[0] == 'T' ) {
1016 } elseif ( in_array( 'H', $flags ) ) {
1017 // replace A flag, and remove other flags except T
1018 $temp = array( '+', 'H' );
1019 if ( in_array( 'T', $flags ) ) {
1022 if ( in_array( 'D', $flags ) ) {
1027 if ( in_array( 'A', $flags ) ) {
1031 if ( in_array( 'D', $flags ) ) {
1032 $flags = array_diff( $flags, array( 'S' ) );
1034 $flags_temp = array();
1035 foreach ( $variants as $variant ) {
1036 // try to find flags like "zh-hans", "zh-hant"
1037 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1038 if ( in_array( $variant, $flags ) )
1039 $flags_temp[] = $variant;
1041 if ( count( $flags_temp ) !== 0 ) {
1042 $flags = $flags_temp;
1045 if ( count( $flags ) == 0 ) {
1046 $flags = array( 'S' );
1048 $this->mRules
= $rules;
1049 $this->mFlags
= $flags;
1053 * Generate conversion table.
1056 function parseRules() {
1057 $rules = $this->mRules
;
1058 $flags = $this->mFlags
;
1059 $bidtable = array();
1060 $unidtable = array();
1061 $markup = $this->mConverter
->mMarkup
;
1062 $variants = $this->mConverter
->mVariants
;
1064 // varsep_pattern for preg_split:
1065 // text should be splited by ";" only if a valid variant
1066 // name exist after the markup, for example:
1067 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1068 // <span style="font-size:120%;">yyy</span>;}-
1069 // we should split it as:
1071 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1072 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1075 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1076 foreach ( $variants as $variant ) {
1077 // zh-hans:xxx;zh-hant:yyy
1078 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|';
1079 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1080 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1081 . '\s*' . $markup['codesep'] . '|';
1083 $varsep_pattern .= '\s*$)/';
1085 $choice = preg_split( $varsep_pattern, $rules );
1087 foreach ( $choice as $c ) {
1088 $v = explode( $markup['codesep'], $c, 2 );
1089 if ( count( $v ) != 2 ) {
1090 // syntax error, skip
1093 $to = trim( $v[1] );
1095 $u = explode( $markup['unidsep'], $v, 2 );
1096 // if $to is empty, strtr() could return a wrong result
1097 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1098 $bidtable[$v] = $to;
1099 } elseif ( count( $u ) == 2 ) {
1100 $from = trim( $u[0] );
1102 if ( array_key_exists( $v, $unidtable )
1103 && !is_array( $unidtable[$v] )
1105 && in_array( $v, $variants ) ) {
1106 $unidtable[$v] = array( $from => $to );
1107 } elseif ( $to && in_array( $v, $variants ) ) {
1108 $unidtable[$v][$from] = $to;
1111 // syntax error, pass
1112 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ) {
1113 $bidtable = array();
1114 $unidtable = array();
1118 $this->mBidtable
= $bidtable;
1119 $this->mUnidtable
= $unidtable;
1125 function getRulesDesc() {
1126 $codesep = $this->mConverter
->mDescCodeSep
;
1127 $varsep = $this->mConverter
->mDescVarSep
;
1129 foreach ( $this->mBidtable
as $k => $v ) {
1130 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1132 foreach ( $this->mUnidtable
as $k => $a ) {
1133 foreach ( $a as $from => $to ) {
1134 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1135 "$codesep$to$varsep";
1142 * Parse rules conversion.
1145 function getRuleConvertedStr( $variant ) {
1146 $bidtable = $this->mBidtable
;
1147 $unidtable = $this->mUnidtable
;
1149 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1150 return $this->mRules
;
1152 // display current variant in bidirectional array
1153 $disp = $this->getTextInBidtable( $variant );
1154 // or display current variant in fallbacks
1156 $disp = $this->getTextInBidtable(
1157 $this->mConverter
->getVariantFallbacks( $variant ) );
1159 // or display current variant in unidirectional array
1160 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1161 $disp = array_values( $unidtable[$variant] );
1164 // or display frist text under disable manual convert
1166 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1167 if ( count( $bidtable ) > 0 ) {
1168 $disp = array_values( $bidtable );
1171 $disp = array_values( $unidtable );
1172 $disp = array_values( $disp[0] );
1181 * Generate conversion table for all text.
1184 function generateConvTable() {
1185 $flags = $this->mFlags
;
1186 $bidtable = $this->mBidtable
;
1187 $unidtable = $this->mUnidtable
;
1188 $manLevel = $this->mConverter
->mManualLevel
;
1191 foreach ( $this->mConverter
->mVariants
as $v ) {
1192 /* for bidirectional array
1193 fill in the missing variants, if any,
1195 if ( !array_key_exists( $v, $bidtable ) ) {
1197 $this->mConverter
->getVariantFallbacks( $v );
1198 $vf = $this->getTextInBidtable( $variantFallbacks );
1200 $bidtable[$v] = $vf;
1204 if ( array_key_exists( $v, $bidtable ) ) {
1205 foreach ( $vmarked as $vo ) {
1206 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1207 // or -{H|zh:WordZh;zh-tw:WordTw}-
1208 // or -{-|zh:WordZh;zh-tw:WordTw}-
1209 // to introduce a custom mapping between
1210 // words WordZh and WordTw in the whole text
1211 if ( $manLevel[$v] == 'bidirectional' ) {
1212 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1214 if ( $manLevel[$vo] == 'bidirectional' ) {
1215 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1220 /*for unidirectional array fill to convert tables */
1221 if ( ( $manLevel[$v] == 'bidirectional'
1222 ||
$manLevel[$v] == 'unidirectional' )
1223 && array_key_exists( $v, $unidtable ) ) {
1224 $ct = $this->mConvTable
[$v];
1225 $this->mConvTable
[$v] = array_merge( $ct, $unidtable[$v] );
1231 * Parse rules and flags.
1234 function parse( $variant = NULL ) {
1236 $variant = $this->mConverter
->getPreferredVariant();
1239 $variants = $this->mConverter
->mVariants
;
1240 $this->parseFlags();
1241 $flags = $this->mFlags
;
1243 // convert to specified variant
1244 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1245 if ( count( array_diff( $flags, $variants ) ) == 0
1246 and count( $flags ) != 0 ) {
1247 // check if current variant in flags
1248 if ( in_array( $variant, $flags ) ) {
1249 // then convert <text to convert> to current language
1250 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1252 } else { // if current variant no in flags,
1253 // then we check its fallback variants.
1255 $this->mConverter
->getVariantFallbacks( $variant );
1256 foreach ( $variantFallbacks as $variantFallback ) {
1257 // if current variant's fallback exist in flags
1258 if ( in_array( $variantFallback, $flags ) ) {
1259 // then convert <text to convert> to fallback language
1261 $this->mConverter
->autoConvert( $this->mRules
,
1267 $this->mFlags
= $flags = array( 'R' );
1270 if ( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1271 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1272 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1274 $this->parseRules();
1276 $rules = $this->mRules
;
1278 if ( count( $this->mBidtable
) == 0
1279 && count( $this->mUnidtable
) == 0 ) {
1280 if ( in_array( '+', $flags ) ||
in_array( '-', $flags ) ) {
1281 // fill all variants if text in -{A/H/-|text} without rules
1282 foreach ( $this->mConverter
->mVariants
as $v ) {
1283 $this->mBidtable
[$v] = $rules;
1285 } elseif ( !in_array( 'N', $flags ) && !in_array( 'T', $flags ) ) {
1286 $this->mFlags
= $flags = array( 'R' );
1290 if ( in_array( 'R', $flags ) ) {
1291 // if we don't do content convert, still strip the -{}- tags
1292 $this->mRuleDisplay
= $rules;
1293 } elseif ( in_array( 'N', $flags ) ) {
1294 // proces N flag: output current variant name
1295 $this->mRuleDisplay
=
1296 $this->mConverter
->mVariantNames
[ trim( $rules ) ];
1297 } elseif ( in_array( 'D', $flags ) ) {
1298 // proces D flag: output rules description
1299 $this->mRuleDisplay
= $this->getRulesDesc();
1300 } elseif ( in_array( 'H', $flags ) ||
in_array( '-', $flags ) ) {
1301 // proces H,- flag or T only: output nothing
1302 $this->mRuleDisplay
= '';
1303 } elseif ( in_array( 'S', $flags ) ) {
1304 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1306 $this->mRuleDisplay
= $this->mManualCodeError
;
1309 if ( in_array( 'T', $flags ) ) {
1310 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1313 if ( in_array( '-', $flags ) ) {
1314 $this->mRulesAction
= 'remove';
1316 if ( in_array( '+', $flags ) ) {
1317 $this->mRulesAction
= 'add';
1320 $this->generateConvTable();
1326 function hasRules() {
1331 * Get display text on markup -{...}-
1334 function getDisplay() {
1335 return $this->mRuleDisplay
;
1339 * Get converted title.
1342 function getTitle() {
1343 return $this->mRuleTitle
;
1347 * Return how deal with conversion rules.
1350 function getRulesAction() {
1351 return $this->mRulesAction
;
1355 * Get conversion table. ( bidirectional and unidirectional
1356 * conversion table )
1359 function getConvTable() {
1360 return $this->mConvTable
;
1364 * Get conversion rules string.
1367 function getRules() {
1368 return $this->mRules
;
1372 * Get conversion flags.
1375 function getFlags() {
1376 return $this->mFlags
;