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 $mPreferredVariant = ''; // The User's preferred variant
20 var $mMainLanguageCode;
21 var $mVariants, $mVariantFallbacks, $mVariantNames;
22 var $mTablesLoaded = false;
24 var $mNamespaceTables;
25 // 'bidirectional' 'unidirectional' 'disable' for each variant
31 var $mDescCodeSep = ':', $mDescVarSep = ';';
32 var $mUcfirst = false;
34 const CACHE_VERSION_KEY
= 'VERSION 6';
39 * @param $langobj The Language Object
40 * @param string $maincode the main language code of this language
41 * @param array $variants the supported variants of this language
42 * @param array $variantfallback the fallback language of each variant
43 * @param array $markup array defining the markup used for manual conversion
44 * @param array $flags array defining the custom strings that maps to the
46 * @param array $manualLevel limit for supported variants
49 function __construct( $langobj, $maincode,
51 $variantfallbacks = array(),
54 $manualLevel = array() ) {
55 $this->mLangObj
= $langobj;
56 $this->mMainLanguageCode
= $maincode;
58 global $wgDisabledVariants;
59 $this->mVariants
= array();
60 foreach ( $variants as $variant ) {
61 if ( !in_array( $variant, $wgDisabledVariants ) ) {
62 $this->mVariants
[] = $variant;
65 $this->mVariantFallbacks
= $variantfallbacks;
66 global $wgLanguageNames;
67 $this->mVariantNames
= $wgLanguageNames;
68 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
72 'unidsep' => '=>', // for unidirectional conversion
77 $this->mMarkup
= array_merge( $m, $markup );
79 // 'S' show converted text
80 // '+' add rules for alltext
81 // 'E' the gave flags is error
82 // these flags above are reserved for program
83 'A' => 'A', // add rule for convert code (all text convert)
84 'T' => 'T', // title convert
85 'R' => 'R', // raw content
86 'D' => 'D', // convert description (subclass implement)
87 '-' => '-', // remove convert (not implement)
88 'H' => 'H', // add rule for convert code
89 // (but no display in placed code )
90 'N' => 'N' // current variant name
92 $this->mFlags
= array_merge( $f, $flags );
93 foreach ( $this->mVariants
as $v ) {
94 if ( array_key_exists( $v, $manualLevel ) ) {
95 $this->mManualLevel
[$v] = $manualLevel[$v];
97 $this->mManualLevel
[$v] = 'bidirectional';
99 $this->mNamespaceTables
[$v] = array();
100 $this->mFlags
[$v] = $v;
107 function getVariants() {
108 return $this->mVariants
;
112 * In case some variant is not defined in the markup, we need
113 * to have some fallback. For example, in zh, normally people
114 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
115 * when zh-sg is preferred but not defined, we will pick zh-hans
116 * in this case. Right now this is only used by zh.
118 * @param string $v The language code of the variant
119 * @return string array The code of the fallback language or false if there
123 function getVariantFallbacks( $v ) {
124 if ( isset( $this->mVariantFallbacks
[$v] ) ) {
125 return $this->mVariantFallbacks
[$v];
127 return $this->mMainLanguageCode
;
131 * Get preferred language variants.
132 * @param boolean $fromUser Get it from $wgUser's preferences
133 * @param boolean $fromHeader Get it from Accept-Language
134 * @return string the preferred language code
137 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
138 global $wgUser, $wgRequest, $wgVariantArticlePath,
139 $wgDefaultLanguageVariant, $wgOut;
141 // see if the preference is set in the request
142 $req = $wgRequest->getText( 'variant' );
143 if ( in_array( $req, $this->mVariants
) ) {
144 $this->mPreferredVariant
= $req;
145 return $this->mPreferredVariant
;
149 // bug 21974, don't return $this->mPreferredVariant if
151 if ( $this->mPreferredVariant
) {
152 return $this->mPreferredVariant
;
155 // figure out user lang without constructing wgLang to avoid
156 // infinite recursion
157 $defaultUserLang = $wgUser->getOption( 'language' );
159 // get language variant preference from logged in users
160 // Don't call this on stub objects because that causes infinite
161 // recursion during initialisation
162 if ( $wgUser->isLoggedIn() ) {
163 $this->mPreferredVariant
= $wgUser->getOption( 'variant' );
167 $defaultUserLang = $this->mMainLanguageCode
;
169 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
171 // see if interface language is same as content, if not, prevent
173 if ( ! in_array( $userLang, $this->mVariants
) ) {
175 $this->mPreferredVariant
= $this->mMainLanguageCode
;
176 return $this->mPreferredVariant
;
177 } elseif ( $this->mPreferredVariant
) {
178 // if the variant was set above and it iss a variant of
179 // the content language
180 return $this->mPreferredVariant
;
183 // see if default variant is globaly set
184 if ( $wgDefaultLanguageVariant != false
185 && in_array( $wgDefaultLanguageVariant, $this->mVariants
) ) {
186 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
187 return $this->mPreferredVariant
;
190 $headerVariant = $this->getHeaderVariant();
191 if ( $fromHeader && $headerVariant ) {
192 return $headerVariant;
195 return $this->mMainLanguageCode
;
199 * Determine the language variant from the Accept-Language header.
201 * @returns mixed variant if one found, false otherwise.
203 function getHeaderVariant() {
206 if ( $this->mHeaderVariant
) {
207 return $this->mHeaderVariant
;
210 // see if some supported language variant is set in the
211 // http header, but we don't set the mPreferredVariant
212 // variable in case this is called before the user's
213 // preference is loaded
215 $acceptLanguage = $wgRequest->getHeader( 'Accept-Language' );
216 if ( !$acceptLanguage ) {
221 $result = explode( ',', strtolower( $acceptLanguage ) );
223 $languages = array();
225 foreach ( $result as $elem ) {
226 // if $elem likes 'zh-cn;q=0.9'
227 if ( ( $posi = strpos( $elem, ';' ) ) !== false ) {
228 // get the real language code likes 'zh-cn'
229 $languages[] = substr( $elem, 0, $posi );
231 $languages[] = $elem;
235 $fallback_languages = array();
236 foreach ( $languages as $language ) {
238 $language = trim( $language );
239 if ( in_array( $language, $this->mVariants
) ) {
240 $this->mHeaderVariant
= $language;
243 // To see if there are fallbacks of current language.
244 // We record these fallback variants, and process
246 $fallbacks = $this->getVariantFallbacks( $language );
247 if ( is_string( $fallbacks ) ) {
248 $fallback_languages[] = $fallbacks;
249 } elseif ( is_array( $fallbacks ) ) {
250 $fallback_languages =
251 array_merge( $fallback_languages,
257 // process fallback languages now
258 $fallback_languages = array_unique( $fallback_languages );
259 foreach ( $fallback_languages as $language ) {
260 if ( in_array( $language, $this->mVariants
) ) {
261 $this->mHeaderVariant
= $language;
268 * Caption convert, base on preg_replace_callback.
270 * To convert text in "title" or "alt", like '<img alt="text" ... '
271 * or '<span title="text" ... '
273 * @return string like ' alt="yyyy"' or ' title="yyyy"'
276 function captionConvert( $matches ) {
277 $toVariant = $this->getPreferredVariant();
278 $title = $matches[1];
280 // we convert captions except URL
281 if ( !strpos( $text, '://' ) ) {
282 $text = $this->translate( $text, $toVariant );
284 return " $title=\"$text\"";
288 * Dictionary-based conversion.
290 * @param string $text the text to be converted
291 * @param string $toVariant the target language code
292 * @return string the converted text
295 function autoConvert( $text, $toVariant = false ) {
296 $fname = 'LanguageConverter::autoConvert';
298 wfProfileIn( $fname );
300 if ( !$this->mTablesLoaded
) {
305 $toVariant = $this->getPreferredVariant();
307 if ( !in_array( $toVariant, $this->mVariants
) ) {
311 /* we convert everything except:
312 1. html markups (anything between < and >)
314 3. place holders created by the parser
317 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
318 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
323 // this one is needed when the text is inside an html markup
324 $htmlfix = '|<[^>]+$|^[^<>]*>';
326 // disable convert to variants between <code></code> tags
327 $codefix = '<code>.+?<\/code>|';
328 // disable convertsion of <script type="text/javascript"> ... </script>
329 $scriptfix = '<script.*?>.*?<\/script>|';
330 // disable conversion of <pre xxxx> ... </pre>
331 $prefix = '<pre.*?>.*?<\/pre>|';
333 $reg = '/' . $codefix . $scriptfix . $prefix .
334 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
336 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
338 $m = array_shift( $matches );
340 $ret = $this->translate( $m[0], $toVariant );
341 $mstart = $m[1] +
strlen( $m[0] );
343 // enable convertsion of '<img alt="xxxx" ... '
344 // or '<span title="xxxx" ... '
345 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
350 foreach ( $matches as $m ) {
351 $mark = substr( $text, $mstart, $m[1] - $mstart );
352 $mark = preg_replace_callback( $captionpattern,
353 array( &$this, 'captionConvert' ),
355 // Let's convert the trtext only once,
356 // it would give us more performance improvement
358 $trtext .= $m[0] . $trtextmark;
359 $mstart = $m[1] +
strlen( $m[0] );
362 $trtext = $this->translate( $trtext, $toVariant );
363 $trtext = StringUtils
::explode( $trtextmark, $trtext );
364 foreach ( $trtext as $t ) {
365 $ret .= array_shift( $notrtext );
368 wfProfileOut( $fname );
373 * Translate a string to a variant.
374 * Doesn't process markup or do any of that other stuff, for that use
377 * @param string $text Text to convert
378 * @param string $variant Variant language code
379 * @return string Translated text
382 function translate( $text, $variant ) {
383 wfProfileIn( __METHOD__
);
384 // If $text is empty or only includes spaces, do nothing
385 // Otherwise translate it
386 if ( trim( $text ) ) {
387 if ( !$this->mTablesLoaded
) {
390 $text = $this->mTables
[$variant]->replace( $text );
392 wfProfileOut( __METHOD__
);
397 * Convert text to all supported variants.
399 * @param string $text the text to be converted
400 * @return array of string
403 function autoConvertToAllVariants( $text ) {
404 $fname = 'LanguageConverter::autoConvertToAllVariants';
405 wfProfileIn( $fname );
406 if ( !$this->mTablesLoaded
) {
411 foreach ( $this->mVariants
as $variant ) {
412 $ret[$variant] = $this->translate( $text, $variant );
415 wfProfileOut( $fname );
420 * Convert link text to all supported variants.
422 * @param string $text the text to be converted
423 * @return array of string
426 function convertLinkToAllVariants( $text ) {
427 if ( !$this->mTablesLoaded
) {
432 $tarray = explode( $this->mMarkup
['begin'], $text );
433 $tfirst = array_shift( $tarray );
435 foreach ( $this->mVariants
as $variant ) {
436 $ret[$variant] = $this->translate( $tfirst, $variant );
439 foreach ( $tarray as $txt ) {
440 $marked = explode( $this->mMarkup
['end'], $txt, 2 );
442 foreach ( $this->mVariants
as $variant ) {
443 $ret[$variant] .= $this->mMarkup
['begin'] . $marked[0] .
444 $this->mMarkup
['end'];
445 if ( array_key_exists( 1, $marked ) ) {
446 $ret[$variant] .= $this->translate( $marked[1], $variant );
456 * Prepare manual conversion table.
459 function applyManualConv( $convRule ) {
460 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom
461 // conversion in title
462 $title = $convRule->getTitle();
464 // apply manual conversion table to global table
465 $convTable = $convRule->getConvTable();
466 $action = $convRule->getRulesAction();
467 foreach ( $convTable as $variant => $pair ) {
468 if ( !in_array( $variant, $this->mVariants
) ) {
472 if ( $action == 'add' ) {
473 foreach ( $pair as $from => $to ) {
474 // to ensure that $from and $to not be left blank
475 // so $this->translate() could always return a string
476 if ( $from ||
$to ) {
477 // more efficient than array_merge(), about 2.5 times.
478 $this->mTables
[$variant]->setPair( $from, $to );
481 } elseif ( $action == 'remove' ) {
482 $this->mTables
[$variant]->removeArray( $pair );
489 * @param string $title the title included namespace
490 * @return array of string
493 function convertNamespace( $title, $variant ) {
494 $splittitle = explode( ':', $title );
495 if ( count( $splittitle ) < 2 ) {
498 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) ) {
499 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
501 $ret = implode( ':', $splittitle );
506 * Convert a text fragment.
508 * @param string $text text to be converted
509 * @param string $plang preferred variant
510 * @return string converted text
513 function convertFragment( $text, $plang ) {
514 $marked = explode( $this->mMarkup
['begin'], $text, 2 );
517 if ( $this->mDoContentConvert
) {
518 // Bug 19620: should convert a string immediately after a
520 $converted .= $this->autoConvert( $marked[0], $plang );
522 $converted .= $marked[0];
525 if ( array_key_exists( 1, $marked ) ) {
526 $crule = new ConverterRule( $marked[1], $this );
527 $crule->parse( $plang );
528 $converted .= $crule->getDisplay();
529 $this->applyManualConv( $crule );
531 $converted .= $this->mMarkup
['end'];
538 * Convert text to different variants of a language. The automatic
539 * conversion is done in autoConvert(). Here we parse the text
540 * marked with -{}-, which specifies special conversions of the
541 * text that can not be accomplished in autoConvert().
543 * Syntax of the markup:
544 * -{code1:text1;code2:text2;...}- or
545 * -{flags|code1:text1;code2:text2;...}- or
546 * -{text}- in which case no conversion should take place for text
548 * @param string $text text to be converted
549 * @return string converted text
552 function convert( $text ) {
553 if ( $wgDisableLangConversion ) return $text;
555 $plang = $this->getPreferredVariant();
556 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
559 foreach ( $tarray as $txt ) {
560 $converted .= $this->convertFragment( $txt, $plang );
563 // Remove the last delimiter (wasn't real)
564 $converted = substr( $converted, 0, - strlen( $this->mMarkup
['end'] ) );
566 error_log("title2: $converted\n");
567 $this->mConvertedTitle
= $converted;
573 * If a language supports multiple variants, it is
574 * possible that non-existing link in one variant
575 * actually exists in another variant. This function
576 * tries to find it. See e.g. LanguageZh.php
578 * @param string $link the name of the link
579 * @param mixed $nt the title object of the link
580 * @param boolean $ignoreOtherCond: to disable other conditions when
581 * we need to transclude a template or update a category's link
582 * @return null the input parameters may be modified upon return
585 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
586 # If the article has already existed, there is no need to
587 # check it again, otherwise it may cause a fault.
588 if ( is_object( $nt ) && $nt->exists() ) {
592 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
594 $isredir = $wgRequest->getText( 'redirect', 'yes' );
595 $action = $wgRequest->getText( 'action' );
596 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
597 $disableLinkConversion = $wgDisableLangConversion
598 ||
$wgDisableTitleConversion;
599 $linkBatch = new LinkBatch();
603 if ( $disableLinkConversion ||
604 ( !$ignoreOtherCond &&
607 ||
$action == 'submit'
608 ||
$linkconvert == 'no'
609 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
613 if ( is_object( $nt ) ) {
614 $ns = $nt->getNamespace();
617 $variants = $this->autoConvertToAllVariants( $link );
618 if ( $variants == false ) { // give up
624 foreach ( $variants as $v ) {
626 $varnt = Title
::newFromText( $v, $ns );
627 if ( !is_null( $varnt ) ) {
628 $linkBatch->addObj( $varnt );
634 // fetch all variants in single query
635 $linkBatch->execute();
637 foreach ( $titles as $varnt ) {
638 if ( $varnt->getArticleID() > 0 ) {
640 $link = $varnt->getText();
647 * Returns language specific hash options.
651 function getExtraHashOptions() {
652 $variant = $this->getPreferredVariant();
653 return '!' . $variant ;
657 * Load default conversion tables.
658 * This method must be implemented in derived class.
662 function loadDefaultTables() {
663 $name = get_class( $this );
664 wfDie( "Must implement loadDefaultTables() method in class $name" );
668 * Load conversion tables either from the cache or the disk.
671 function loadTables( $fromcache = true ) {
673 if ( $this->mTablesLoaded
) {
676 wfProfileIn( __METHOD__
);
677 $this->mTablesLoaded
= true;
678 $this->mTables
= false;
680 wfProfileIn( __METHOD__
. '-cache' );
681 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
682 wfProfileOut( __METHOD__
. '-cache' );
685 ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
686 wfProfileIn( __METHOD__
. '-recache' );
687 // not in cache, or we need a fresh reload.
688 // we will first load the default tables
689 // then update them using things in MediaWiki:Zhconversiontable/*
690 $this->loadDefaultTables();
691 foreach ( $this->mVariants
as $var ) {
692 $cached = $this->parseCachedTable( $var );
693 $this->mTables
[$var]->mergeArray( $cached );
696 $this->postLoadTables();
697 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
699 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
700 wfProfileOut( __METHOD__
. '-recache' );
702 wfProfileOut( __METHOD__
);
706 * Hook for post processig after conversion tables are loaded.
709 function postLoadTables() { }
712 * Reload the conversion tables.
716 function reloadTables() {
717 if ( $this->mTables
) {
718 unset( $this->mTables
);
720 $this->mTablesLoaded
= false;
721 $this->loadTables( false );
726 * Parse the conversion table stored in the cache.
728 * The tables should be in blocks of the following form:
735 * To make the tables more manageable, subpages are allowed
736 * and will be parsed recursively if $recursive == true.
739 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
740 global $wgMessageCache;
741 static $parsed = array();
743 if ( !is_object( $wgMessageCache ) ) {
747 $key = 'Conversiontable/' . $code;
749 $key .= '/' . $subpage;
751 if ( array_key_exists( $key, $parsed ) ) {
755 if ( strpos( $code, '/' ) === false ) {
756 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
758 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
759 "Conversiontable/$code" );
760 if ( $title && $title->exists() ) {
761 $article = new Article( $title );
762 $txt = $article->getContents();
768 // get all subpage links of the form
769 // [[MediaWiki:conversiontable/zh-xx/...|...]]
770 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
772 $subs = explode( '[[', $txt );
774 foreach ( $subs as $sub ) {
775 $link = explode( ']]', $sub, 2 );
776 if ( count( $link ) != 2 ) {
779 $b = explode( '|', $link[0] );
780 $b = explode( '/', trim( $b[0] ), 3 );
781 if ( count( $b ) == 3 ) {
787 if ( $b[0] == $linkhead && $b[1] == $code ) {
788 $sublinks[] = $sublink;
793 // parse the mappings in this page
794 $blocks = explode( $this->mMarkup
['begin'], $txt );
795 array_shift( $blocks );
797 foreach ( $blocks as $block ) {
798 $mappings = explode( $this->mMarkup
['end'], $block, 2 );
799 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
801 $table = explode( ';', $stripped );
802 foreach ( $table as $t ) {
803 $m = explode( '=>', $t );
804 if ( count( $m ) != 2 )
806 // trim any trailling comments starting with '//'
807 $tt = explode( '//', $m[1], 2 );
808 $ret[trim( $m[0] )] = trim( $tt[0] );
811 $parsed[$key] = true;
814 // recursively parse the subpages
816 foreach ( $sublinks as $link ) {
817 $s = $this->parseCachedTable( $code, $link, $recursive );
818 $ret = array_merge( $ret, $s );
822 if ( $this->mUcfirst
) {
823 foreach ( $ret as $k => $v ) {
824 $ret[Language
::ucfirst( $k )] = Language
::ucfirst( $v );
831 * Enclose a string with the "no conversion" tag. This is used by
832 * various functions in the Parser.
834 * @param string $text text to be tagged for no conversion
835 * @return string the tagged text
838 function markNoConversion( $text, $noParse = false ) {
839 # don't mark if already marked
840 if ( strpos( $text, $this->mMarkup
['begin'] )
841 ||
strpos( $text, $this->mMarkup
['end'] ) ) {
845 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
850 * Convert the sorting key for category links. This should make different
851 * keys that are variants of each other map to the same key.
853 function convertCategoryKey( $key ) {
858 * Hook to refresh the cache of conversion tables when
859 * MediaWiki:conversiontable* is updated.
862 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
863 $iswatch, $section, $flags, $revision ) {
864 $titleobj = $article->getTitle();
865 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
866 $title = $titleobj->getDBkey();
867 $t = explode( '/', $title, 3 );
869 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
870 if ( in_array( $t[1], $this->mVariants
) ) {
871 $this->reloadTables();
879 * Armour rendered math against conversion.
880 * Wrap math into rawoutput -{R| math }- syntax.
883 function armourMath( $text ) {
884 // we need to convert '-{' and '}-' to '-{' and '}-'
885 // to avoid a unwanted '}-' appeared after the math-image.
886 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
887 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
893 * Parser for rules of language conversion , parse rules in -{ }- tag.
895 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
897 class ConverterRule
{
898 var $mText; // original text in -{text}-
899 var $mConverter; // LanguageConverter object
900 var $mManualCodeError = '<strong class="error">code error!</strong>';
901 var $mRuleDisplay = '';
902 var $mRuleTitle = false;
903 var $mRules = '';// string : the text of the rules
904 var $mRulesAction = 'none';
905 var $mFlags = array();
906 var $mConvTable = array();
907 var $mBidtable = array();// array of the translation in each variant
908 var $mUnidtable = array();// array of the translation in each variant
913 * @param string $text the text between -{ and }-
914 * @param object $converter a LanguageConverter object
917 function __construct( $text, $converter ) {
918 $this->mText
= $text;
919 $this->mConverter
= $converter;
920 foreach ( $converter->mVariants
as $v ) {
921 $this->mConvTable
[$v] = array();
926 * Check if variants array in convert array.
928 * @param string $variant Variant language code
929 * @return string Translated text
932 function getTextInBidtable( $variants ) {
933 if ( is_string( $variants ) ) {
934 $variants = array( $variants );
936 if ( !is_array( $variants ) ) {
939 foreach ( $variants as $variant ) {
940 if ( array_key_exists( $variant, $this->mBidtable
) ) {
941 return $this->mBidtable
[$variant];
948 * Parse flags with syntax -{FLAG| ... }-
951 function parseFlags() {
952 $text = $this->mText
;
953 if ( strlen( $text ) < 2 ) {
954 $this->mFlags
= array( 'R' );
955 $this->mRules
= $text;
960 $markup = $this->mConverter
->mMarkup
;
961 $validFlags = $this->mConverter
->mFlags
;
962 $variants = $this->mConverter
->mVariants
;
964 $tt = explode( $markup['flagsep'], $text, 2 );
965 if ( count( $tt ) == 2 ) {
966 $f = explode( $markup['varsep'], $tt[0] );
967 foreach ( $f as $ff ) {
969 if ( array_key_exists( $ff, $validFlags )
970 && !in_array( $validFlags[$ff], $flags ) ) {
971 $flags[] = $validFlags[$ff];
980 if ( in_array( 'R', $flags ) ) {
981 $flags = array( 'R' );// remove other flags
982 } elseif ( in_array( 'N', $flags ) ) {
983 $flags = array( 'N' );// remove other flags
984 } elseif ( in_array( '-', $flags ) ) {
985 $flags = array( '-' );// remove other flags
986 } elseif ( count( $flags ) == 1 && $flags[0] == 'T' ) {
988 } elseif ( in_array( 'H', $flags ) ) {
989 // replace A flag, and remove other flags except T
990 $temp = array( '+', 'H' );
991 if ( in_array( 'T', $flags ) ) {
994 if ( in_array( 'D', $flags ) ) {
999 if ( in_array( 'A', $flags ) ) {
1003 if ( in_array( 'D', $flags ) ) {
1004 $flags = array_diff( $flags, array( 'S' ) );
1006 $flags_temp = array();
1007 foreach ( $variants as $variant ) {
1008 // try to find flags like "zh-hans", "zh-hant"
1009 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1010 if ( in_array( $variant, $flags ) )
1011 $flags_temp[] = $variant;
1013 if ( count( $flags_temp ) !== 0 ) {
1014 $flags = $flags_temp;
1017 if ( count( $flags ) == 0 ) {
1018 $flags = array( 'S' );
1020 $this->mRules
= $rules;
1021 $this->mFlags
= $flags;
1025 * Generate conversion table.
1028 function parseRules() {
1029 $rules = $this->mRules
;
1030 $flags = $this->mFlags
;
1031 $bidtable = array();
1032 $unidtable = array();
1033 $markup = $this->mConverter
->mMarkup
;
1034 $variants = $this->mConverter
->mVariants
;
1036 // varsep_pattern for preg_split:
1037 // text should be splited by ";" only if a valid variant
1038 // name exist after the markup, for example:
1039 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1040 // <span style="font-size:120%;">yyy</span>;}-
1041 // we should split it as:
1043 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1044 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1047 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1048 foreach ( $variants as $variant ) {
1049 // zh-hans:xxx;zh-hant:yyy
1050 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|';
1051 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1052 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1053 . '\s*' . $markup['codesep'] . '|';
1055 $varsep_pattern .= '\s*$)/';
1057 $choice = preg_split( $varsep_pattern, $rules );
1059 foreach ( $choice as $c ) {
1060 $v = explode( $markup['codesep'], $c, 2 );
1061 if ( count( $v ) != 2 ) {
1062 // syntax error, skip
1065 $to = trim( $v[1] );
1067 $u = explode( $markup['unidsep'], $v, 2 );
1068 // if $to is empty, strtr() could return a wrong result
1069 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1070 $bidtable[$v] = $to;
1071 } elseif ( count( $u ) == 2 ) {
1072 $from = trim( $u[0] );
1074 if ( array_key_exists( $v, $unidtable )
1075 && !is_array( $unidtable[$v] )
1077 && in_array( $v, $variants ) ) {
1078 $unidtable[$v] = array( $from => $to );
1079 } elseif ( $to && in_array( $v, $variants ) ) {
1080 $unidtable[$v][$from] = $to;
1083 // syntax error, pass
1084 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ) {
1085 $bidtable = array();
1086 $unidtable = array();
1090 $this->mBidtable
= $bidtable;
1091 $this->mUnidtable
= $unidtable;
1097 function getRulesDesc() {
1098 $codesep = $this->mConverter
->mDescCodeSep
;
1099 $varsep = $this->mConverter
->mDescVarSep
;
1101 foreach ( $this->mBidtable
as $k => $v ) {
1102 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1104 foreach ( $this->mUnidtable
as $k => $a ) {
1105 foreach ( $a as $from => $to ) {
1106 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1107 "$codesep$to$varsep";
1114 * Parse rules conversion.
1117 function getRuleConvertedStr( $variant, $doConvert ) {
1118 $bidtable = $this->mBidtable
;
1119 $unidtable = $this->mUnidtable
;
1121 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1122 return $this->mRules
;
1123 } elseif ( $doConvert ) { // the text converted
1124 // display current variant in bidirectional array
1125 $disp = $this->getTextInBidtable( $variant );
1126 // or display current variant in fallbacks
1128 $disp = $this->getTextInBidtable(
1129 $this->mConverter
->getVariantFallbacks( $variant ) );
1131 // or display current variant in unidirectional array
1132 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1133 $disp = array_values( $unidtable[$variant] );
1136 // or display frist text under disable manual convert
1138 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1139 if ( count( $bidtable ) > 0 ) {
1140 $disp = array_values( $bidtable );
1143 $disp = array_values( $unidtable );
1144 $disp = array_values( $disp[0] );
1149 } else { // no convert
1150 return $this->mRules
;
1155 * Generate conversion table for all text.
1158 function generateConvTable() {
1159 $flags = $this->mFlags
;
1160 $bidtable = $this->mBidtable
;
1161 $unidtable = $this->mUnidtable
;
1162 $manLevel = $this->mConverter
->mManualLevel
;
1165 foreach ( $this->mConverter
->mVariants
as $v ) {
1166 /* for bidirectional array
1167 fill in the missing variants, if any,
1169 if ( !array_key_exists( $v, $bidtable ) ) {
1171 $this->mConverter
->getVariantFallbacks( $v );
1172 $vf = $this->getTextInBidtable( $variantFallbacks );
1174 $bidtable[$v] = $vf;
1178 if ( array_key_exists( $v, $bidtable ) ) {
1179 foreach ( $vmarked as $vo ) {
1180 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1181 // or -{H|zh:WordZh;zh-tw:WordTw}-
1182 // or -{-|zh:WordZh;zh-tw:WordTw}-
1183 // to introduce a custom mapping between
1184 // words WordZh and WordTw in the whole text
1185 if ( $manLevel[$v] == 'bidirectional' ) {
1186 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1188 if ( $manLevel[$vo] == 'bidirectional' ) {
1189 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1194 /*for unidirectional array fill to convert tables */
1195 if ( ( $manLevel[$v] == 'bidirectional'
1196 ||
$manLevel[$v] == 'unidirectional' )
1197 && array_key_exists( $v, $unidtable ) ) {
1198 $ct = $this->mConvTable
[$v];
1199 $this->mConvTable
[$v] = array_merge( $ct, $unidtable[$v] );
1205 * Parse rules and flags.
1208 function parse( $variant = NULL ) {
1210 $variant = $this->mConverter
->getPreferredVariant();
1213 $variants = $this->mConverter
->mVariants
;
1214 $this->parseFlags();
1215 $flags = $this->mFlags
;
1217 // convert to specified variant
1218 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1219 if ( count( array_diff( $flags, $variants ) ) == 0
1220 and count( $flags ) != 0 ) {
1221 // check if current variant in flags
1222 if ( in_array( $variant, $flags ) ) {
1223 // then convert <text to convert> to current language
1224 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1226 } else { // if current variant no in flags,
1227 // then we check its fallback variants.
1229 $this->mConverter
->getVariantFallbacks( $variant );
1230 foreach ( $variantFallbacks as $variantFallback ) {
1231 // if current variant's fallback exist in flags
1232 if ( in_array( $variantFallback, $flags ) ) {
1233 // then convert <text to convert> to fallback language
1235 $this->mConverter
->autoConvert( $this->mRules
,
1241 $this->mFlags
= $flags = array( 'R' );
1244 if ( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1245 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1246 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1248 $this->parseRules();
1250 $rules = $this->mRules
;
1252 if ( count( $this->mBidtable
) == 0
1253 && count( $this->mUnidtable
) == 0 ) {
1254 if ( in_array( '+', $flags ) ||
in_array( '-', $flags ) ) {
1255 // fill all variants if text in -{A/H/-|text} without rules
1256 foreach ( $this->mConverter
->mVariants
as $v ) {
1257 $this->mBidtable
[$v] = $rules;
1259 } elseif ( !in_array( 'N', $flags ) && !in_array( 'T', $flags ) ) {
1260 $this->mFlags
= $flags = array( 'R' );
1264 if ( in_array( 'R', $flags ) ) {
1265 // if we don't do content convert, still strip the -{}- tags
1266 $this->mRuleDisplay
= $rules;
1267 } elseif ( in_array( 'N', $flags ) ) {
1268 // proces N flag: output current variant name
1269 $this->mRuleDisplay
=
1270 $this->mConverter
->mVariantNames
[ trim( $rules ) ];
1271 } elseif ( in_array( 'D', $flags ) ) {
1272 // proces D flag: output rules description
1273 $this->mRuleDisplay
= $this->getRulesDesc();
1274 } elseif ( in_array( 'H', $flags ) ||
in_array( '-', $flags ) ) {
1275 // proces H,- flag or T only: output nothing
1276 $this->mRuleDisplay
= '';
1277 } elseif ( in_array( 'S', $flags ) ) {
1278 // true hard-coded now since we shouldn't be called if we're not converting
1279 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant, true );
1281 $this->mRuleDisplay
= $this->mManualCodeError
;
1284 if ( in_array( 'T', $flags ) ) {
1285 // true hard-coded now since we shouldn't be called if we're not converting
1286 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant, true );
1289 if ( in_array( '-', $flags ) ) {
1290 $this->mRulesAction
= 'remove';
1292 if ( in_array( '+', $flags ) ) {
1293 $this->mRulesAction
= 'add';
1296 $this->generateConvTable();
1302 function hasRules() {
1307 * Get display text on markup -{...}-
1310 function getDisplay() {
1311 return $this->mRuleDisplay
;
1315 * Get converted title.
1318 function getTitle() {
1319 return $this->mRuleTitle
;
1323 * Return how deal with conversion rules.
1326 function getRulesAction() {
1327 return $this->mRulesAction
;
1331 * Get conversion table. ( bidirectional and unidirectional
1332 * conversion table )
1335 function getConvTable() {
1336 return $this->mConvTable
;
1340 * Get conversion rules string.
1343 function getRules() {
1344 return $this->mRules
;
1348 * Get conversion flags.
1351 function getFlags() {
1352 return $this->mFlags
;