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 var $mConvRuleTitle = false;
36 const CACHE_VERSION_KEY
= 'VERSION 6';
41 * @param $langobj The Language Object
42 * @param string $maincode the main language code of this language
43 * @param array $variants the supported variants of this language
44 * @param array $variantfallback the fallback language of each variant
45 * @param array $markup array defining the markup used for manual conversion
46 * @param array $flags array defining the custom strings that maps to the
48 * @param array $manualLevel limit for supported variants
51 function __construct( $langobj, $maincode,
53 $variantfallbacks = array(),
56 $manualLevel = array() ) {
57 $this->mLangObj
= $langobj;
58 $this->mMainLanguageCode
= $maincode;
60 global $wgDisabledVariants;
61 $this->mVariants
= array();
62 foreach ( $variants as $variant ) {
63 if ( !in_array( $variant, $wgDisabledVariants ) ) {
64 $this->mVariants
[] = $variant;
67 $this->mVariantFallbacks
= $variantfallbacks;
68 global $wgLanguageNames;
69 $this->mVariantNames
= $wgLanguageNames;
70 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
74 'unidsep' => '=>', // for unidirectional conversion
79 $this->mMarkup
= array_merge( $m, $markup );
81 // 'S' show converted text
82 // '+' add rules for alltext
83 // 'E' the gave flags is error
84 // these flags above are reserved for program
85 'A' => 'A', // add rule for convert code (all text convert)
86 'T' => 'T', // title convert
87 'R' => 'R', // raw content
88 'D' => 'D', // convert description (subclass implement)
89 '-' => '-', // remove convert (not implement)
90 'H' => 'H', // add rule for convert code
91 // (but no display in placed code )
92 'N' => 'N' // current variant name
94 $this->mFlags
= array_merge( $f, $flags );
95 foreach ( $this->mVariants
as $v ) {
96 if ( array_key_exists( $v, $manualLevel ) ) {
97 $this->mManualLevel
[$v] = $manualLevel[$v];
99 $this->mManualLevel
[$v] = 'bidirectional';
101 $this->mNamespaceTables
[$v] = array();
102 $this->mFlags
[$v] = $v;
109 function getVariants() {
110 return $this->mVariants
;
114 * In case some variant is not defined in the markup, we need
115 * to have some fallback. For example, in zh, normally people
116 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
117 * when zh-sg is preferred but not defined, we will pick zh-hans
118 * in this case. Right now this is only used by zh.
120 * @param string $v The language code of the variant
121 * @return string array The code of the fallback language or false if there
125 function getVariantFallbacks( $v ) {
126 if ( isset( $this->mVariantFallbacks
[$v] ) ) {
127 return $this->mVariantFallbacks
[$v];
129 return $this->mMainLanguageCode
;
133 * Get preferred language variants.
134 * @param boolean $fromUser Get it from $wgUser's preferences
135 * @param boolean $fromHeader Get it from Accept-Language
136 * @return string the preferred language code
139 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
140 global $wgUser, $wgRequest, $wgVariantArticlePath,
141 $wgDefaultLanguageVariant, $wgOut;
143 // see if the preference is set in the request
144 $req = $wgRequest->getText( 'variant' );
145 if ( in_array( $req, $this->mVariants
) ) {
146 $this->mPreferredVariant
= $req;
147 return $this->mPreferredVariant
;
151 // bug 21974, don't return $this->mPreferredVariant if
153 if ( $this->mPreferredVariant
) {
154 return $this->mPreferredVariant
;
157 // figure out user lang without constructing wgLang to avoid
158 // infinite recursion
159 $defaultUserLang = $wgUser->getOption( 'language' );
161 // get language variant preference from logged in users
162 // Don't call this on stub objects because that causes infinite
163 // recursion during initialisation
164 if ( $wgUser->isLoggedIn() ) {
165 $this->mPreferredVariant
= $wgUser->getOption( 'variant' );
169 $defaultUserLang = $this->mMainLanguageCode
;
171 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
173 // see if interface language is same as content, if not, prevent
175 if ( ! in_array( $userLang, $this->mVariants
) ) {
177 $this->mPreferredVariant
= $this->mMainLanguageCode
;
178 return $this->mPreferredVariant
;
179 } elseif ( $this->mPreferredVariant
) {
180 // if the variant was set above and it iss a variant of
181 // the content language
182 return $this->mPreferredVariant
;
185 // see if default variant is globaly set
186 if ( $wgDefaultLanguageVariant != false
187 && in_array( $wgDefaultLanguageVariant, $this->mVariants
) ) {
188 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
189 return $this->mPreferredVariant
;
192 $headerVariant = $this->getHeaderVariant();
193 if ( $fromHeader && $headerVariant ) {
194 return $headerVariant;
197 return $this->mMainLanguageCode
;
201 * Determine the language variant from the Accept-Language header.
203 * @returns mixed variant if one found, false otherwise.
205 function getHeaderVariant() {
208 if ( $this->mHeaderVariant
) {
209 return $this->mHeaderVariant
;
212 // see if some supported language variant is set in the
213 // http header, but we don't set the mPreferredVariant
214 // variable in case this is called before the user's
215 // preference is loaded
217 $acceptLanguage = $wgRequest->getHeader( 'Accept-Language' );
218 if ( !$acceptLanguage ) {
223 $result = explode( ',', strtolower( $acceptLanguage ) );
225 $languages = array();
227 foreach ( $result as $elem ) {
228 // if $elem likes 'zh-cn;q=0.9'
229 if ( ( $posi = strpos( $elem, ';' ) ) !== false ) {
230 // get the real language code likes 'zh-cn'
231 $languages[] = substr( $elem, 0, $posi );
233 $languages[] = $elem;
237 $fallback_languages = array();
238 foreach ( $languages as $language ) {
240 $language = trim( $language );
241 if ( in_array( $language, $this->mVariants
) ) {
242 $this->mHeaderVariant
= $language;
245 // To see if there are fallbacks of current language.
246 // We record these fallback variants, and process
248 $fallbacks = $this->getVariantFallbacks( $language );
249 if ( is_string( $fallbacks ) ) {
250 $fallback_languages[] = $fallbacks;
251 } elseif ( is_array( $fallbacks ) ) {
252 $fallback_languages =
253 array_merge( $fallback_languages,
259 // process fallback languages now
260 $fallback_languages = array_unique( $fallback_languages );
261 foreach ( $fallback_languages as $language ) {
262 if ( in_array( $language, $this->mVariants
) ) {
263 $this->mHeaderVariant
= $language;
270 * Caption convert, base on preg_replace_callback.
272 * To convert text in "title" or "alt", like '<img alt="text" ... '
273 * or '<span title="text" ... '
275 * @return string like ' alt="yyyy"' or ' title="yyyy"'
278 function captionConvert( $matches ) {
279 $toVariant = $this->getPreferredVariant();
280 $title = $matches[1];
282 // we convert captions except URL
283 if ( !strpos( $text, '://' ) ) {
284 $text = $this->translate( $text, $toVariant );
286 return " $title=\"$text\"";
290 * Dictionary-based conversion.
292 * @param string $text the text to be converted
293 * @param string $toVariant the target language code
294 * @return string the converted text
297 function autoConvert( $text, $toVariant = false ) {
298 $fname = 'LanguageConverter::autoConvert';
300 wfProfileIn( $fname );
302 if ( !$this->mTablesLoaded
) {
307 $toVariant = $this->getPreferredVariant();
309 if ( !in_array( $toVariant, $this->mVariants
) ) {
313 /* we convert everything except:
314 1. html markups (anything between < and >)
316 3. place holders created by the parser
319 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
320 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
325 // this one is needed when the text is inside an html markup
326 $htmlfix = '|<[^>]+$|^[^<>]*>';
328 // disable convert to variants between <code></code> tags
329 $codefix = '<code>.+?<\/code>|';
330 // disable convertsion of <script type="text/javascript"> ... </script>
331 $scriptfix = '<script.*?>.*?<\/script>|';
332 // disable conversion of <pre xxxx> ... </pre>
333 $prefix = '<pre.*?>.*?<\/pre>|';
335 $reg = '/' . $codefix . $scriptfix . $prefix .
336 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
338 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
340 $m = array_shift( $matches );
342 $ret = $this->translate( $m[0], $toVariant );
343 $mstart = $m[1] +
strlen( $m[0] );
345 // enable convertsion of '<img alt="xxxx" ... '
346 // or '<span title="xxxx" ... '
347 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
352 foreach ( $matches as $m ) {
353 $mark = substr( $text, $mstart, $m[1] - $mstart );
354 $mark = preg_replace_callback( $captionpattern,
355 array( &$this, 'captionConvert' ),
357 // Let's convert the trtext only once,
358 // it would give us more performance improvement
360 $trtext .= $m[0] . $trtextmark;
361 $mstart = $m[1] +
strlen( $m[0] );
364 $trtext = $this->translate( $trtext, $toVariant );
365 $trtext = StringUtils
::explode( $trtextmark, $trtext );
366 foreach ( $trtext as $t ) {
367 $ret .= array_shift( $notrtext );
370 wfProfileOut( $fname );
375 * Translate a string to a variant.
376 * Doesn't process markup or do any of that other stuff, for that use
379 * @param string $text Text to convert
380 * @param string $variant Variant language code
381 * @return string Translated text
384 function translate( $text, $variant ) {
385 wfProfileIn( __METHOD__
);
386 // If $text is empty or only includes spaces, do nothing
387 // Otherwise translate it
388 if ( trim( $text ) ) {
389 if ( !$this->mTablesLoaded
) {
392 $text = $this->mTables
[$variant]->replace( $text );
394 wfProfileOut( __METHOD__
);
399 * Convert text to all supported variants.
401 * @param string $text the text to be converted
402 * @return array of string
405 function autoConvertToAllVariants( $text ) {
406 $fname = 'LanguageConverter::autoConvertToAllVariants';
407 wfProfileIn( $fname );
408 if ( !$this->mTablesLoaded
) {
413 foreach ( $this->mVariants
as $variant ) {
414 $ret[$variant] = $this->translate( $text, $variant );
417 wfProfileOut( $fname );
422 * Convert link text to all supported variants.
424 * @param string $text the text to be converted
425 * @return array of string
428 function convertLinkToAllVariants( $text ) {
429 if ( !$this->mTablesLoaded
) {
434 $tarray = explode( $this->mMarkup
['begin'], $text );
435 $tfirst = array_shift( $tarray );
437 foreach ( $this->mVariants
as $variant ) {
438 $ret[$variant] = $this->translate( $tfirst, $variant );
441 foreach ( $tarray as $txt ) {
442 $marked = explode( $this->mMarkup
['end'], $txt, 2 );
444 foreach ( $this->mVariants
as $variant ) {
445 $ret[$variant] .= $this->mMarkup
['begin'] . $marked[0] .
446 $this->mMarkup
['end'];
447 if ( array_key_exists( 1, $marked ) ) {
448 $ret[$variant] .= $this->translate( $marked[1], $variant );
458 * Prepare manual conversion table.
461 function applyManualConv( $convRule ) {
462 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom
463 // conversion in title
464 $this->mConvRuleTitle
= $convRule->getTitle();
466 // apply manual conversion table to global table
467 $convTable = $convRule->getConvTable();
468 $action = $convRule->getRulesAction();
469 foreach ( $convTable as $variant => $pair ) {
470 if ( !in_array( $variant, $this->mVariants
) ) {
474 if ( $action == 'add' ) {
475 foreach ( $pair as $from => $to ) {
476 // to ensure that $from and $to not be left blank
477 // so $this->translate() could always return a string
478 if ( $from ||
$to ) {
479 // more efficient than array_merge(), about 2.5 times.
480 $this->mTables
[$variant]->setPair( $from, $to );
483 } elseif ( $action == 'remove' ) {
484 $this->mTables
[$variant]->removeArray( $pair );
491 * @param string $title the title included namespace
492 * @return array of string
495 function convertNamespace( $title, $variant ) {
496 $splittitle = explode( ':', $title );
497 if ( count( $splittitle ) < 2 ) {
500 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) ) {
501 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
503 $ret = implode( ':', $splittitle );
508 * Convert a text fragment.
510 * @param string $text text to be converted
511 * @param string $plang preferred variant
512 * @return string converted text
515 function convertFragment( $text, $plang ) {
516 $marked = explode( $this->mMarkup
['begin'], $text, 2 );
519 $converted .= $this->autoConvert( $marked[0], $plang );
521 if ( array_key_exists( 1, $marked ) ) {
522 $crule = new ConverterRule( $marked[1], $this );
523 $crule->parse( $plang );
524 $converted .= $crule->getDisplay();
525 $this->applyManualConv( $crule );
527 $converted .= $this->mMarkup
['end'];
534 * Convert text to different variants of a language. The automatic
535 * conversion is done in autoConvert(). Here we parse the text
536 * marked with -{}-, which specifies special conversions of the
537 * text that can not be accomplished in autoConvert().
539 * Syntax of the markup:
540 * -{code1:text1;code2:text2;...}- or
541 * -{flags|code1:text1;code2:text2;...}- or
542 * -{text}- in which case no conversion should take place for text
544 * @param string $text text to be converted
545 * @return string converted text
548 function convert( $text ) {
549 global $wgDisableLangConversion;
550 if ( $wgDisableLangConversion ) return $text;
552 $plang = $this->getPreferredVariant();
553 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
556 foreach ( $tarray as $txt ) {
557 $converted .= $this->convertFragment( $txt, $plang );
560 // Remove the last delimiter (wasn't real)
561 $converted = substr( $converted, 0, - strlen( $this->mMarkup
['end'] ) );
566 * If a language supports multiple variants, it is
567 * possible that non-existing link in one variant
568 * actually exists in another variant. This function
569 * tries to find it. See e.g. LanguageZh.php
571 * @param string $link the name of the link
572 * @param mixed $nt the title object of the link
573 * @param boolean $ignoreOtherCond: to disable other conditions when
574 * we need to transclude a template or update a category's link
575 * @return null the input parameters may be modified upon return
578 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
579 # If the article has already existed, there is no need to
580 # check it again, otherwise it may cause a fault.
581 if ( is_object( $nt ) && $nt->exists() ) {
585 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
587 $isredir = $wgRequest->getText( 'redirect', 'yes' );
588 $action = $wgRequest->getText( 'action' );
589 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
590 $disableLinkConversion = $wgDisableLangConversion
591 ||
$wgDisableTitleConversion;
592 $linkBatch = new LinkBatch();
596 if ( $disableLinkConversion ||
597 ( !$ignoreOtherCond &&
600 ||
$action == 'submit'
601 ||
$linkconvert == 'no'
602 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
606 if ( is_object( $nt ) ) {
607 $ns = $nt->getNamespace();
610 $variants = $this->autoConvertToAllVariants( $link );
611 if ( $variants == false ) { // give up
617 foreach ( $variants as $v ) {
619 $varnt = Title
::newFromText( $v, $ns );
620 if ( !is_null( $varnt ) ) {
621 $linkBatch->addObj( $varnt );
627 // fetch all variants in single query
628 $linkBatch->execute();
630 foreach ( $titles as $varnt ) {
631 if ( $varnt->getArticleID() > 0 ) {
633 $link = $varnt->getText();
640 * Returns language specific hash options.
644 function getExtraHashOptions() {
645 $variant = $this->getPreferredVariant();
646 return '!' . $variant ;
650 * Load default conversion tables.
651 * This method must be implemented in derived class.
655 function loadDefaultTables() {
656 $name = get_class( $this );
657 wfDie( "Must implement loadDefaultTables() method in class $name" );
661 * Load conversion tables either from the cache or the disk.
664 function loadTables( $fromcache = true ) {
666 if ( $this->mTablesLoaded
) {
669 wfProfileIn( __METHOD__
);
670 $this->mTablesLoaded
= true;
671 $this->mTables
= false;
673 wfProfileIn( __METHOD__
. '-cache' );
674 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
675 wfProfileOut( __METHOD__
. '-cache' );
678 ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
679 wfProfileIn( __METHOD__
. '-recache' );
680 // not in cache, or we need a fresh reload.
681 // we will first load the default tables
682 // then update them using things in MediaWiki:Zhconversiontable/*
683 $this->loadDefaultTables();
684 foreach ( $this->mVariants
as $var ) {
685 $cached = $this->parseCachedTable( $var );
686 $this->mTables
[$var]->mergeArray( $cached );
689 $this->postLoadTables();
690 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
692 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
693 wfProfileOut( __METHOD__
. '-recache' );
695 wfProfileOut( __METHOD__
);
699 * Hook for post processig after conversion tables are loaded.
702 function postLoadTables() { }
705 * Reload the conversion tables.
709 function reloadTables() {
710 if ( $this->mTables
) {
711 unset( $this->mTables
);
713 $this->mTablesLoaded
= false;
714 $this->loadTables( false );
719 * Parse the conversion table stored in the cache.
721 * The tables should be in blocks of the following form:
728 * To make the tables more manageable, subpages are allowed
729 * and will be parsed recursively if $recursive == true.
732 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
733 global $wgMessageCache;
734 static $parsed = array();
736 if ( !is_object( $wgMessageCache ) ) {
740 $key = 'Conversiontable/' . $code;
742 $key .= '/' . $subpage;
744 if ( array_key_exists( $key, $parsed ) ) {
748 if ( strpos( $code, '/' ) === false ) {
749 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
751 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
752 "Conversiontable/$code" );
753 if ( $title && $title->exists() ) {
754 $article = new Article( $title );
755 $txt = $article->getContents();
761 // get all subpage links of the form
762 // [[MediaWiki:conversiontable/zh-xx/...|...]]
763 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
765 $subs = explode( '[[', $txt );
767 foreach ( $subs as $sub ) {
768 $link = explode( ']]', $sub, 2 );
769 if ( count( $link ) != 2 ) {
772 $b = explode( '|', $link[0] );
773 $b = explode( '/', trim( $b[0] ), 3 );
774 if ( count( $b ) == 3 ) {
780 if ( $b[0] == $linkhead && $b[1] == $code ) {
781 $sublinks[] = $sublink;
786 // parse the mappings in this page
787 $blocks = explode( $this->mMarkup
['begin'], $txt );
788 array_shift( $blocks );
790 foreach ( $blocks as $block ) {
791 $mappings = explode( $this->mMarkup
['end'], $block, 2 );
792 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
794 $table = explode( ';', $stripped );
795 foreach ( $table as $t ) {
796 $m = explode( '=>', $t );
797 if ( count( $m ) != 2 )
799 // trim any trailling comments starting with '//'
800 $tt = explode( '//', $m[1], 2 );
801 $ret[trim( $m[0] )] = trim( $tt[0] );
804 $parsed[$key] = true;
807 // recursively parse the subpages
809 foreach ( $sublinks as $link ) {
810 $s = $this->parseCachedTable( $code, $link, $recursive );
811 $ret = array_merge( $ret, $s );
815 if ( $this->mUcfirst
) {
816 foreach ( $ret as $k => $v ) {
817 $ret[Language
::ucfirst( $k )] = Language
::ucfirst( $v );
824 * Enclose a string with the "no conversion" tag. This is used by
825 * various functions in the Parser.
827 * @param string $text text to be tagged for no conversion
828 * @return string the tagged text
831 function markNoConversion( $text, $noParse = false ) {
832 # don't mark if already marked
833 if ( strpos( $text, $this->mMarkup
['begin'] )
834 ||
strpos( $text, $this->mMarkup
['end'] ) ) {
838 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
843 * Convert the sorting key for category links. This should make different
844 * keys that are variants of each other map to the same key.
846 function convertCategoryKey( $key ) {
851 * Hook to refresh the cache of conversion tables when
852 * MediaWiki:conversiontable* is updated.
855 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
856 $iswatch, $section, $flags, $revision ) {
857 $titleobj = $article->getTitle();
858 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
859 $title = $titleobj->getDBkey();
860 $t = explode( '/', $title, 3 );
862 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
863 if ( in_array( $t[1], $this->mVariants
) ) {
864 $this->reloadTables();
872 * Armour rendered math against conversion.
873 * Wrap math into rawoutput -{R| math }- syntax.
876 function armourMath( $text ) {
877 // we need to convert '-{' and '}-' to '-{' and '}-'
878 // to avoid a unwanted '}-' appeared after the math-image.
879 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
880 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
886 * Parser for rules of language conversion , parse rules in -{ }- tag.
888 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
890 class ConverterRule
{
891 var $mText; // original text in -{text}-
892 var $mConverter; // LanguageConverter object
893 var $mManualCodeError = '<strong class="error">code error!</strong>';
894 var $mRuleDisplay = '';
895 var $mRuleTitle = false;
896 var $mRules = '';// string : the text of the rules
897 var $mRulesAction = 'none';
898 var $mFlags = array();
899 var $mConvTable = array();
900 var $mBidtable = array();// array of the translation in each variant
901 var $mUnidtable = array();// array of the translation in each variant
906 * @param string $text the text between -{ and }-
907 * @param object $converter a LanguageConverter object
910 function __construct( $text, $converter ) {
911 $this->mText
= $text;
912 $this->mConverter
= $converter;
913 foreach ( $converter->mVariants
as $v ) {
914 $this->mConvTable
[$v] = array();
919 * Check if variants array in convert array.
921 * @param string $variant Variant language code
922 * @return string Translated text
925 function getTextInBidtable( $variants ) {
926 if ( is_string( $variants ) ) {
927 $variants = array( $variants );
929 if ( !is_array( $variants ) ) {
932 foreach ( $variants as $variant ) {
933 if ( array_key_exists( $variant, $this->mBidtable
) ) {
934 return $this->mBidtable
[$variant];
941 * Parse flags with syntax -{FLAG| ... }-
944 function parseFlags() {
945 $text = $this->mText
;
946 if ( strlen( $text ) < 2 ) {
947 $this->mFlags
= array( 'R' );
948 $this->mRules
= $text;
953 $markup = $this->mConverter
->mMarkup
;
954 $validFlags = $this->mConverter
->mFlags
;
955 $variants = $this->mConverter
->mVariants
;
957 $tt = explode( $markup['flagsep'], $text, 2 );
958 if ( count( $tt ) == 2 ) {
959 $f = explode( $markup['varsep'], $tt[0] );
960 foreach ( $f as $ff ) {
962 if ( array_key_exists( $ff, $validFlags )
963 && !in_array( $validFlags[$ff], $flags ) ) {
964 $flags[] = $validFlags[$ff];
973 if ( in_array( 'R', $flags ) ) {
974 $flags = array( 'R' );// remove other flags
975 } elseif ( in_array( 'N', $flags ) ) {
976 $flags = array( 'N' );// remove other flags
977 } elseif ( in_array( '-', $flags ) ) {
978 $flags = array( '-' );// remove other flags
979 } elseif ( count( $flags ) == 1 && $flags[0] == 'T' ) {
981 } elseif ( in_array( 'H', $flags ) ) {
982 // replace A flag, and remove other flags except T
983 $temp = array( '+', 'H' );
984 if ( in_array( 'T', $flags ) ) {
987 if ( in_array( 'D', $flags ) ) {
992 if ( in_array( 'A', $flags ) ) {
996 if ( in_array( 'D', $flags ) ) {
997 $flags = array_diff( $flags, array( 'S' ) );
999 $flags_temp = array();
1000 foreach ( $variants as $variant ) {
1001 // try to find flags like "zh-hans", "zh-hant"
1002 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1003 if ( in_array( $variant, $flags ) )
1004 $flags_temp[] = $variant;
1006 if ( count( $flags_temp ) !== 0 ) {
1007 $flags = $flags_temp;
1010 if ( count( $flags ) == 0 ) {
1011 $flags = array( 'S' );
1013 $this->mRules
= $rules;
1014 $this->mFlags
= $flags;
1018 * Generate conversion table.
1021 function parseRules() {
1022 $rules = $this->mRules
;
1023 $flags = $this->mFlags
;
1024 $bidtable = array();
1025 $unidtable = array();
1026 $markup = $this->mConverter
->mMarkup
;
1027 $variants = $this->mConverter
->mVariants
;
1029 // varsep_pattern for preg_split:
1030 // text should be splited by ";" only if a valid variant
1031 // name exist after the markup, for example:
1032 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1033 // <span style="font-size:120%;">yyy</span>;}-
1034 // we should split it as:
1036 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1037 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1040 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1041 foreach ( $variants as $variant ) {
1042 // zh-hans:xxx;zh-hant:yyy
1043 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|';
1044 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1045 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1046 . '\s*' . $markup['codesep'] . '|';
1048 $varsep_pattern .= '\s*$)/';
1050 $choice = preg_split( $varsep_pattern, $rules );
1052 foreach ( $choice as $c ) {
1053 $v = explode( $markup['codesep'], $c, 2 );
1054 if ( count( $v ) != 2 ) {
1055 // syntax error, skip
1058 $to = trim( $v[1] );
1060 $u = explode( $markup['unidsep'], $v, 2 );
1061 // if $to is empty, strtr() could return a wrong result
1062 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1063 $bidtable[$v] = $to;
1064 } elseif ( count( $u ) == 2 ) {
1065 $from = trim( $u[0] );
1067 if ( array_key_exists( $v, $unidtable )
1068 && !is_array( $unidtable[$v] )
1070 && in_array( $v, $variants ) ) {
1071 $unidtable[$v] = array( $from => $to );
1072 } elseif ( $to && in_array( $v, $variants ) ) {
1073 $unidtable[$v][$from] = $to;
1076 // syntax error, pass
1077 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ) {
1078 $bidtable = array();
1079 $unidtable = array();
1083 $this->mBidtable
= $bidtable;
1084 $this->mUnidtable
= $unidtable;
1090 function getRulesDesc() {
1091 $codesep = $this->mConverter
->mDescCodeSep
;
1092 $varsep = $this->mConverter
->mDescVarSep
;
1094 foreach ( $this->mBidtable
as $k => $v ) {
1095 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1097 foreach ( $this->mUnidtable
as $k => $a ) {
1098 foreach ( $a as $from => $to ) {
1099 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1100 "$codesep$to$varsep";
1107 * Parse rules conversion.
1110 function getRuleConvertedStr( $variant ) {
1111 $bidtable = $this->mBidtable
;
1112 $unidtable = $this->mUnidtable
;
1114 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1115 return $this->mRules
;
1117 // display current variant in bidirectional array
1118 $disp = $this->getTextInBidtable( $variant );
1119 // or display current variant in fallbacks
1121 $disp = $this->getTextInBidtable(
1122 $this->mConverter
->getVariantFallbacks( $variant ) );
1124 // or display current variant in unidirectional array
1125 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1126 $disp = array_values( $unidtable[$variant] );
1129 // or display frist text under disable manual convert
1131 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1132 if ( count( $bidtable ) > 0 ) {
1133 $disp = array_values( $bidtable );
1136 $disp = array_values( $unidtable );
1137 $disp = array_values( $disp[0] );
1146 * Generate conversion table for all text.
1149 function generateConvTable() {
1150 $flags = $this->mFlags
;
1151 $bidtable = $this->mBidtable
;
1152 $unidtable = $this->mUnidtable
;
1153 $manLevel = $this->mConverter
->mManualLevel
;
1156 foreach ( $this->mConverter
->mVariants
as $v ) {
1157 /* for bidirectional array
1158 fill in the missing variants, if any,
1160 if ( !array_key_exists( $v, $bidtable ) ) {
1162 $this->mConverter
->getVariantFallbacks( $v );
1163 $vf = $this->getTextInBidtable( $variantFallbacks );
1165 $bidtable[$v] = $vf;
1169 if ( array_key_exists( $v, $bidtable ) ) {
1170 foreach ( $vmarked as $vo ) {
1171 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1172 // or -{H|zh:WordZh;zh-tw:WordTw}-
1173 // or -{-|zh:WordZh;zh-tw:WordTw}-
1174 // to introduce a custom mapping between
1175 // words WordZh and WordTw in the whole text
1176 if ( $manLevel[$v] == 'bidirectional' ) {
1177 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1179 if ( $manLevel[$vo] == 'bidirectional' ) {
1180 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1185 /*for unidirectional array fill to convert tables */
1186 if ( ( $manLevel[$v] == 'bidirectional'
1187 ||
$manLevel[$v] == 'unidirectional' )
1188 && array_key_exists( $v, $unidtable ) ) {
1189 $ct = $this->mConvTable
[$v];
1190 $this->mConvTable
[$v] = array_merge( $ct, $unidtable[$v] );
1196 * Parse rules and flags.
1199 function parse( $variant = NULL ) {
1201 $variant = $this->mConverter
->getPreferredVariant();
1204 $variants = $this->mConverter
->mVariants
;
1205 $this->parseFlags();
1206 $flags = $this->mFlags
;
1208 // convert to specified variant
1209 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1210 if ( count( array_diff( $flags, $variants ) ) == 0
1211 and count( $flags ) != 0 ) {
1212 // check if current variant in flags
1213 if ( in_array( $variant, $flags ) ) {
1214 // then convert <text to convert> to current language
1215 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1217 } else { // if current variant no in flags,
1218 // then we check its fallback variants.
1220 $this->mConverter
->getVariantFallbacks( $variant );
1221 foreach ( $variantFallbacks as $variantFallback ) {
1222 // if current variant's fallback exist in flags
1223 if ( in_array( $variantFallback, $flags ) ) {
1224 // then convert <text to convert> to fallback language
1226 $this->mConverter
->autoConvert( $this->mRules
,
1232 $this->mFlags
= $flags = array( 'R' );
1235 if ( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1236 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1237 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1239 $this->parseRules();
1241 $rules = $this->mRules
;
1243 if ( count( $this->mBidtable
) == 0
1244 && count( $this->mUnidtable
) == 0 ) {
1245 if ( in_array( '+', $flags ) ||
in_array( '-', $flags ) ) {
1246 // fill all variants if text in -{A/H/-|text} without rules
1247 foreach ( $this->mConverter
->mVariants
as $v ) {
1248 $this->mBidtable
[$v] = $rules;
1250 } elseif ( !in_array( 'N', $flags ) && !in_array( 'T', $flags ) ) {
1251 $this->mFlags
= $flags = array( 'R' );
1255 if ( in_array( 'R', $flags ) ) {
1256 // if we don't do content convert, still strip the -{}- tags
1257 $this->mRuleDisplay
= $rules;
1258 } elseif ( in_array( 'N', $flags ) ) {
1259 // proces N flag: output current variant name
1260 $this->mRuleDisplay
=
1261 $this->mConverter
->mVariantNames
[ trim( $rules ) ];
1262 } elseif ( in_array( 'D', $flags ) ) {
1263 // proces D flag: output rules description
1264 $this->mRuleDisplay
= $this->getRulesDesc();
1265 } elseif ( in_array( 'H', $flags ) ||
in_array( '-', $flags ) ) {
1266 // proces H,- flag or T only: output nothing
1267 $this->mRuleDisplay
= '';
1268 } elseif ( in_array( 'S', $flags ) ) {
1269 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1271 $this->mRuleDisplay
= $this->mManualCodeError
;
1274 if ( in_array( 'T', $flags ) ) {
1275 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1278 if ( in_array( '-', $flags ) ) {
1279 $this->mRulesAction
= 'remove';
1281 if ( in_array( '+', $flags ) ) {
1282 $this->mRulesAction
= 'add';
1285 $this->generateConvTable();
1291 function hasRules() {
1296 * Get display text on markup -{...}-
1299 function getDisplay() {
1300 return $this->mRuleDisplay
;
1304 * Get converted title.
1307 function getTitle() {
1308 return $this->mRuleTitle
;
1312 * Return how deal with conversion rules.
1315 function getRulesAction() {
1316 return $this->mRulesAction
;
1320 * Get conversion table. ( bidirectional and unidirectional
1321 * conversion table )
1324 function getConvTable() {
1325 return $this->mConvTable
;
1329 * Get conversion rules string.
1332 function getRules() {
1333 return $this->mRules
;
1337 * Get conversion flags.
1340 function getFlags() {
1341 return $this->mFlags
;