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 = '';
20 var $mMainLanguageCode;
21 var $mVariants, $mVariantFallbacks, $mVariantNames;
22 var $mTablesLoaded = false;
24 var $mNamespaceTables;
25 var $mDoTitleConvert = true, $mDoContentConvert = true;
26 // 'bidirectional' 'unidirectional' 'disable' for each variant
28 var $mTitleFromFlag = false;
33 var $mDescCodeSep = ':', $mDescVarSep = ';';
34 var $mUcfirst = false;
35 var $mTitleOriginal = '';
36 var $mTitleDisplay = '';
38 const CACHE_VERSION_KEY
= 'VERSION 6';
43 * @param $langobj The Language Object
44 * @param string $maincode the main language code of this language
45 * @param array $variants the supported variants of this language
46 * @param array $variantfallback the fallback language of each variant
47 * @param array $markup array defining the markup used for manual conversion
48 * @param array $flags array defining the custom strings that maps to the
50 * @param array $manualLevel limit for supported variants
53 function __construct( $langobj, $maincode,
55 $variantfallbacks = array(),
58 $manualLevel = array() ) {
59 $this->mLangObj
= $langobj;
60 $this->mMainLanguageCode
= $maincode;
62 global $wgDisabledVariants;
63 $this->mVariants
= array();
64 foreach ( $variants as $variant ) {
65 if ( !in_array( $variant, $wgDisabledVariants ) ) {
66 $this->mVariants
[] = $variant;
69 $this->mVariantFallbacks
= $variantfallbacks;
70 global $wgLanguageNames;
71 $this->mVariantNames
= $wgLanguageNames;
72 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
76 'unidsep' => '=>', // for unidirectional conversion
81 $this->mMarkup
= array_merge( $m, $markup );
83 // 'S' show converted text
84 // '+' add rules for alltext
85 // 'E' the gave flags is error
86 // these flags above are reserved for program
87 'A' => 'A', // add rule for convert code (all text convert)
88 'T' => 'T', // title convert
89 'R' => 'R', // raw content
90 'D' => 'D', // convert description (subclass implement)
91 '-' => '-', // remove convert (not implement)
92 'H' => 'H', // add rule for convert code
93 // (but no display in placed code )
94 'N' => 'N' // current variant name
96 $this->mFlags
= array_merge( $f, $flags );
97 foreach ( $this->mVariants
as $v ) {
98 if ( array_key_exists( $v, $manualLevel ) ) {
99 $this->mManualLevel
[$v] = $manualLevel[$v];
101 $this->mManualLevel
[$v] = 'bidirectional';
103 $this->mNamespaceTables
[$v] = array();
104 $this->mFlags
[$v] = $v;
111 function getVariants() {
112 return $this->mVariants
;
116 * In case some variant is not defined in the markup, we need
117 * to have some fallback. For example, in zh, normally people
118 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
119 * when zh-sg is preferred but not defined, we will pick zh-hans
120 * in this case. Right now this is only used by zh.
122 * @param string $v The language code of the variant
123 * @return string array The code of the fallback language or false if there
127 function getVariantFallbacks( $v ) {
128 if ( isset( $this->mVariantFallbacks
[$v] ) ) {
129 return $this->mVariantFallbacks
[$v];
131 return $this->mMainLanguageCode
;
135 * Get preferred language variants.
136 * @param boolean $fromUser Get it from $wgUser's preferences
137 * @param boolean $fromHeader Get it from Accept-Language
138 * @return string the preferred language code
141 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
142 global $wgUser, $wgRequest, $wgVariantArticlePath,
143 $wgDefaultLanguageVariant, $wgOut;
145 // bug 21974, don't return $this->mPreferredVariant if $fromUser = false
146 if ( $fromUser && $this->mPreferredVariant
) {
147 return $this->mPreferredVariant
;
150 // figure out user lang without constructing wgLang to avoid
151 // infinite recursion
153 $defaultUserLang = $wgUser->getOption( 'language' );
155 $defaultUserLang = $this->mMainLanguageCode
;
158 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
159 // see if interface language is same as content, if not, prevent
162 if ( ! in_array( $userLang, $this->mVariants
) ) {
164 $this->mPreferredVariant
= $this->mMainLanguageCode
;
165 return $this->mPreferredVariant
;
168 // see if the preference is set in the request
169 $req = $wgRequest->getText( 'variant' );
170 if ( in_array( $req, $this->mVariants
) ) {
171 $this->mPreferredVariant
= $req;
172 return $this->mPreferredVariant
;
175 // get language variant preference from logged in users
176 // Don't call this on stub objects because that causes infinite
177 // recursion during initialisation
178 if ( $fromUser && $wgUser->isLoggedIn() ) {
179 $this->mPreferredVariant
= $wgUser->getOption( 'variant' );
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 if ( !$this->mPreferredVariant
) {
191 // see if some supported language variant is set in the
192 // http header, but we don't set the mPreferredVariant
193 // variable in case this is called before the user's
194 // preference is loaded
196 $acceptLanguage = $wgRequest->getHeader( 'Accept-Language' );
197 if ( $fromHeader && $acceptLanguage ) {
199 $result = explode( ',', strtolower( $acceptLanguage ) );
201 $languages = array();
203 foreach ( $result as $elem ) {
204 // if $elem likes 'zh-cn;q=0.9'
205 if ( ( $posi = strpos( $elem, ';' ) ) !== false ) {
206 // get the real language code likes 'zh-cn'
207 $languages[] = substr( $elem, 0, $posi );
209 $languages[] = $elem;
213 $fallback_languages = array();
214 foreach ( $languages as $language ) {
216 $language = trim( $language );
217 if ( in_array( $language, $this->mVariants
) ) {
220 // To see if there are fallbacks of current language.
221 // We record these fallback variants, and process
223 $fallbacks = $this->getVariantFallbacks( $language );
224 if ( is_string( $fallbacks ) ) {
225 $fallback_languages[] = $fallbacks;
226 } elseif ( is_array( $fallbacks ) ) {
227 $fallback_languages =
228 array_merge( $fallback_languages,
234 // process fallback languages now
235 $fallback_languages = array_unique( $fallback_languages );
236 foreach ( $fallback_languages as $language ) {
237 if ( in_array( $language, $this->mVariants
) ) {
243 return $this->mMainLanguageCode
;
247 * Caption convert, base on preg_replace_callback.
249 * To convert text in "title" or "alt", like '<img alt="text" ... '
250 * or '<span title="text" ... '
252 * @return string like ' alt="yyyy"' or ' title="yyyy"'
255 function captionConvert( $matches ) {
256 $toVariant = $this->getPreferredVariant();
257 $title = $matches[1];
259 // we convert captions except URL
260 if ( !strpos( $text, '://' ) ) {
261 $text = $this->translate( $text, $toVariant );
263 return " $title=\"$text\"";
267 * Dictionary-based conversion.
269 * @param string $text the text to be converted
270 * @param string $toVariant the target language code
271 * @return string the converted text
274 function autoConvert( $text, $toVariant = false ) {
275 $fname = 'LanguageConverter::autoConvert';
277 wfProfileIn( $fname );
279 if ( !$this->mTablesLoaded
) {
284 $toVariant = $this->getPreferredVariant();
286 if ( !in_array( $toVariant, $this->mVariants
) ) {
290 /* we convert everything except:
291 1. html markups (anything between < and >)
293 3. place holders created by the parser
296 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
297 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
302 // this one is needed when the text is inside an html markup
303 $htmlfix = '|<[^>]+$|^[^<>]*>';
305 // disable convert to variants between <code></code> tags
306 $codefix = '<code>.+?<\/code>|';
307 // disable convertsion of <script type="text/javascript"> ... </script>
308 $scriptfix = '<script.*?>.*?<\/script>|';
309 // disable conversion of <pre xxxx> ... </pre>
310 $prefix = '<pre.*?>.*?<\/pre>|';
312 $reg = '/' . $codefix . $scriptfix . $prefix .
313 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
315 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
317 $m = array_shift( $matches );
319 $ret = $this->translate( $m[0], $toVariant );
320 $mstart = $m[1] +
strlen( $m[0] );
322 // enable convertsion of '<img alt="xxxx" ... '
323 // or '<span title="xxxx" ... '
324 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
329 foreach ( $matches as $m ) {
330 $mark = substr( $text, $mstart, $m[1] - $mstart );
331 $mark = preg_replace_callback( $captionpattern,
332 array( &$this, 'captionConvert' ),
334 // Let's convert the trtext only once,
335 // it would give us more performance improvement
337 $trtext .= $m[0] . $trtextmark;
338 $mstart = $m[1] +
strlen( $m[0] );
341 $trtext = $this->translate( $trtext, $toVariant );
342 $trtext = StringUtils
::explode( $trtextmark, $trtext );
343 foreach ( $trtext as $t ) {
344 $ret .= array_shift( $notrtext );
347 wfProfileOut( $fname );
352 * Translate a string to a variant.
353 * Doesn't process markup or do any of that other stuff, for that use
356 * @param string $text Text to convert
357 * @param string $variant Variant language code
358 * @return string Translated text
361 function translate( $text, $variant ) {
362 wfProfileIn( __METHOD__
);
363 // If $text is empty or only includes spaces, do nothing
364 // Otherwise translate it
365 if ( trim( $text ) ) {
366 if ( !$this->mTablesLoaded
) {
369 $text = $this->mTables
[$variant]->replace( $text );
371 wfProfileOut( __METHOD__
);
376 * Convert text to all supported variants.
378 * @param string $text the text to be converted
379 * @return array of string
382 function autoConvertToAllVariants( $text ) {
383 $fname = 'LanguageConverter::autoConvertToAllVariants';
384 wfProfileIn( $fname );
385 if ( !$this->mTablesLoaded
) {
390 foreach ( $this->mVariants
as $variant ) {
391 $ret[$variant] = $this->translate( $text, $variant );
394 wfProfileOut( $fname );
399 * Convert link text to all supported variants.
401 * @param string $text the text to be converted
402 * @return array of string
405 function convertLinkToAllVariants( $text ) {
406 if ( !$this->mTablesLoaded
) {
411 $tarray = explode( $this->mMarkup
['begin'], $text );
412 $tfirst = array_shift( $tarray );
414 foreach ( $this->mVariants
as $variant ) {
415 $ret[$variant] = $this->translate( $tfirst, $variant );
418 foreach ( $tarray as $txt ) {
419 $marked = explode( $this->mMarkup
['end'], $txt, 2 );
421 foreach ( $this->mVariants
as $variant ) {
422 $ret[$variant] .= $this->mMarkup
['begin'] . $marked[0] .
423 $this->mMarkup
['end'];
424 if ( array_key_exists( 1, $marked ) ) {
425 $ret[$variant] .= $this->translate( $marked[1], $variant );
435 * Prepare manual conversion table.
438 function applyManualConv( $convRule ) {
439 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom
440 // conversion in title
441 $title = $convRule->getTitle();
443 $this->mTitleFromFlag
= true;
444 $this->mTitleDisplay
= $title;
447 // apply manual conversion table to global table
448 $convTable = $convRule->getConvTable();
449 $action = $convRule->getRulesAction();
450 foreach ( $convTable as $variant => $pair ) {
451 if ( !in_array( $variant, $this->mVariants
) ) {
455 if ( $action == 'add' ) {
456 foreach ( $pair as $from => $to ) {
457 // to ensure that $from and $to not be left blank
458 // so $this->translate() could always return a string
459 if ( $from ||
$to ) {
460 // more efficient than array_merge(), about 2.5 times.
461 $this->mTables
[$variant]->setPair( $from, $to );
464 } elseif ( $action == 'remove' ) {
465 $this->mTables
[$variant]->removeArray( $pair );
471 * Convert text using a parser object for context.
474 function parserConvert( $text, &$parser ) {
475 global $wgDisableLangConversion;
476 /* don't do anything if this is the conversion table */
477 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
478 && strpos( $parser->mTitle
->getText(),
479 'Conversiontable' ) !== false ) {
483 if ( $wgDisableLangConversion ) {
487 $text = $this->convert( $text );
489 $this->convertTitle();
490 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
497 * @param string $title the title included namespace
498 * @return array of string
501 function convertNamespace( $title, $variant ) {
502 $splittitle = explode( ':', $title );
503 if ( count( $splittitle ) < 2 ) {
506 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) ) {
507 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
509 $ret = implode( ':', $splittitle );
514 * Pre convert title. Store the original title $this->mTitleOrginal;
515 * store the default converted title to $this->mTitleDisplay.
518 function preConvertTitle( $text, $variant ) {
519 $this->mTitleOriginal
= $text;
521 $text = $this->convertNamespace( $text, $variant );
522 $this->mTitleDisplay
= $this->convert( $text );
529 function convertTitle() {
530 global $wgDisableTitleConversion, $wgUser, $wgRequest;
531 $isredir = $wgRequest->getText( 'redirect', 'yes' );
532 $action = $wgRequest->getText( 'action' );
533 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
535 // check for the global variable, __NOTC__ magic word, and user setting
536 if ( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
537 $wgUser->getOption( 'noconvertlink' ) == 1 ) {
538 $this->mTitleDisplay
= $this->mTitleOriginal
;
539 } elseif ( $isredir == 'no'
541 ||
$linkconvert == 'no' ) {
542 // check for GET params
543 $this->mTitleDisplay
= $this->mTitleOriginal
;
548 * Convert text to different variants of a language. The automatic
549 * conversion is done in autoConvert(). Here we parse the text
550 * marked with -{}-, which specifies special conversions of the
551 * text that can not be accomplished in autoConvert().
553 * Syntax of the markup:
554 * -{code1:text1;code2:text2;...}- or
555 * -{flags|code1:text1;code2:text2;...}- or
556 * -{text}- in which case no conversion should take place for text
558 * @param string $text text to be converted
559 * @param bool $isTitle whether this conversion is for the article title
560 * @return string converted text
563 function convert( $text, $isTitle = false ) {
565 $mw =& MagicWord
::get( 'notitleconvert' );
566 if ( $mw->matchAndRemove( $text ) ) {
567 $this->mDoTitleConvert
= false;
569 $mw =& MagicWord
::get( 'nocontentconvert' );
570 if ( $mw->matchAndRemove( $text ) ) {
571 $this->mDoContentConvert
= false;
574 // no conversion if redirecting
575 $mw =& MagicWord
::get( 'redirect' );
576 if ( $mw->matchStart( $text ) ) {
580 $plang = $this->getPreferredVariant();
582 // for title convertion
584 $this->preConvertTitle( $text, $plang );
588 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
591 foreach ( $tarray as $txt ) {
593 $marked = explode( $this->mMarkup
['begin'], $txt, 2 );
595 if ( $this->mDoContentConvert
) {
596 // Bug 19620: should convert a string immediately after a
598 $text .= $this->autoConvert( $marked[0], $plang );
603 if ( array_key_exists( 1, $marked ) ) {
604 $crule = new ConverterRule( $marked[1], $this );
605 $crule->parse( $plang );
606 $text .= $crule->getDisplay();
607 $this->applyManualConv( $crule );
609 $text .= $this->mMarkup
['end'];
613 // Remove the last delimiter (wasn't real)
614 $text = substr( $text, 0, - strlen( $this->mMarkup
['end'] ) );
619 * If a language supports multiple variants, it is
620 * possible that non-existing link in one variant
621 * actually exists in another variant. This function
622 * tries to find it. See e.g. LanguageZh.php
624 * @param string $link the name of the link
625 * @param mixed $nt the title object of the link
626 * @param boolean $ignoreOtherCond: to disable other conditions when
627 * we need to transclude a template or update a category's link
628 * @return null the input parameters may be modified upon return
631 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
632 # If the article has already existed, there is no need to
633 # check it again, otherwise it may cause a fault.
634 if ( is_object( $nt ) && $nt->exists() ) {
638 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
640 $isredir = $wgRequest->getText( 'redirect', 'yes' );
641 $action = $wgRequest->getText( 'action' );
642 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
643 $disableLinkConversion = $wgDisableLangConversion
644 ||
$wgDisableTitleConversion;
645 $linkBatch = new LinkBatch();
649 if ( $disableLinkConversion ||
650 ( !$ignoreOtherCond &&
653 ||
$action == 'submit'
654 ||
$linkconvert == 'no'
655 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
659 if ( is_object( $nt ) ) {
660 $ns = $nt->getNamespace();
663 $variants = $this->autoConvertToAllVariants( $link );
664 if ( $variants == false ) { // give up
670 foreach ( $variants as $v ) {
672 $varnt = Title
::newFromText( $v, $ns );
673 if ( !is_null( $varnt ) ) {
674 $linkBatch->addObj( $varnt );
680 // fetch all variants in single query
681 $linkBatch->execute();
683 foreach ( $titles as $varnt ) {
684 if ( $varnt->getArticleID() > 0 ) {
686 $link = $varnt->getText();
693 * Returns language specific hash options.
697 function getExtraHashOptions() {
698 $variant = $this->getPreferredVariant();
699 return '!' . $variant ;
703 * Get title text as defined in the body of the article text.
707 function getParsedTitle() {
708 return $this->mTitleDisplay
;
712 * Load default conversion tables.
713 * This method must be implemented in derived class.
717 function loadDefaultTables() {
718 $name = get_class( $this );
719 wfDie( "Must implement loadDefaultTables() method in class $name" );
723 * Load conversion tables either from the cache or the disk.
726 function loadTables( $fromcache = true ) {
728 if ( $this->mTablesLoaded
) {
731 wfProfileIn( __METHOD__
);
732 $this->mTablesLoaded
= true;
733 $this->mTables
= false;
735 wfProfileIn( __METHOD__
. '-cache' );
736 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
737 wfProfileOut( __METHOD__
. '-cache' );
740 ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
741 wfProfileIn( __METHOD__
. '-recache' );
742 // not in cache, or we need a fresh reload.
743 // we will first load the default tables
744 // then update them using things in MediaWiki:Zhconversiontable/*
745 $this->loadDefaultTables();
746 foreach ( $this->mVariants
as $var ) {
747 $cached = $this->parseCachedTable( $var );
748 $this->mTables
[$var]->mergeArray( $cached );
751 $this->postLoadTables();
752 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
754 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
755 wfProfileOut( __METHOD__
. '-recache' );
757 wfProfileOut( __METHOD__
);
761 * Hook for post processig after conversion tables are loaded.
764 function postLoadTables() { }
767 * Reload the conversion tables.
771 function reloadTables() {
772 if ( $this->mTables
) {
773 unset( $this->mTables
);
775 $this->mTablesLoaded
= false;
776 $this->loadTables( false );
781 * Parse the conversion table stored in the cache.
783 * The tables should be in blocks of the following form:
790 * To make the tables more manageable, subpages are allowed
791 * and will be parsed recursively if $recursive == true.
794 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
795 global $wgMessageCache;
796 static $parsed = array();
798 if ( !is_object( $wgMessageCache ) ) {
802 $key = 'Conversiontable/' . $code;
804 $key .= '/' . $subpage;
806 if ( array_key_exists( $key, $parsed ) ) {
810 if ( strpos( $code, '/' ) === false ) {
811 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
813 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
814 "Conversiontable/$code" );
815 if ( $title && $title->exists() ) {
816 $article = new Article( $title );
817 $txt = $article->getContents();
823 // get all subpage links of the form
824 // [[MediaWiki:conversiontable/zh-xx/...|...]]
825 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
827 $subs = explode( '[[', $txt );
829 foreach ( $subs as $sub ) {
830 $link = explode( ']]', $sub, 2 );
831 if ( count( $link ) != 2 ) {
834 $b = explode( '|', $link[0] );
835 $b = explode( '/', trim( $b[0] ), 3 );
836 if ( count( $b ) == 3 ) {
842 if ( $b[0] == $linkhead && $b[1] == $code ) {
843 $sublinks[] = $sublink;
848 // parse the mappings in this page
849 $blocks = explode( $this->mMarkup
['begin'], $txt );
850 array_shift( $blocks );
852 foreach ( $blocks as $block ) {
853 $mappings = explode( $this->mMarkup
['end'], $block, 2 );
854 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
856 $table = explode( ';', $stripped );
857 foreach ( $table as $t ) {
858 $m = explode( '=>', $t );
859 if ( count( $m ) != 2 )
861 // trim any trailling comments starting with '//'
862 $tt = explode( '//', $m[1], 2 );
863 $ret[trim( $m[0] )] = trim( $tt[0] );
866 $parsed[$key] = true;
869 // recursively parse the subpages
871 foreach ( $sublinks as $link ) {
872 $s = $this->parseCachedTable( $code, $link, $recursive );
873 $ret = array_merge( $ret, $s );
877 if ( $this->mUcfirst
) {
878 foreach ( $ret as $k => $v ) {
879 $ret[Language
::ucfirst( $k )] = Language
::ucfirst( $v );
886 * Enclose a string with the "no conversion" tag. This is used by
887 * various functions in the Parser.
889 * @param string $text text to be tagged for no conversion
890 * @return string the tagged text
893 function markNoConversion( $text, $noParse = false ) {
894 # don't mark if already marked
895 if ( strpos( $text, $this->mMarkup
['begin'] )
896 ||
strpos( $text, $this->mMarkup
['end'] ) ) {
900 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
905 * Convert the sorting key for category links. This should make different
906 * keys that are variants of each other map to the same key.
908 function convertCategoryKey( $key ) {
913 * Hook to refresh the cache of conversion tables when
914 * MediaWiki:conversiontable* is updated.
917 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
918 $iswatch, $section, $flags, $revision ) {
919 $titleobj = $article->getTitle();
920 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
921 $title = $titleobj->getDBkey();
922 $t = explode( '/', $title, 3 );
924 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
925 if ( in_array( $t[1], $this->mVariants
) ) {
926 $this->reloadTables();
934 * Armour rendered math against conversion.
935 * Wrap math into rawoutput -{R| math }- syntax.
938 function armourMath( $text ) {
939 // we need to convert '-{' and '}-' to '-{' and '}-'
940 // to avoid a unwanted '}-' appeared after the math-image.
941 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
942 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
948 * Parser for rules of language conversion , parse rules in -{ }- tag.
950 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
952 class ConverterRule
{
953 var $mText; // original text in -{text}-
954 var $mConverter; // LanguageConverter object
955 var $mManualCodeError = '<strong class="error">code error!</strong>';
956 var $mRuleDisplay = '';
957 var $mRuleTitle = false;
958 var $mRules = '';// string : the text of the rules
959 var $mRulesAction = 'none';
960 var $mFlags = array();
961 var $mConvTable = array();
962 var $mBidtable = array();// array of the translation in each variant
963 var $mUnidtable = array();// array of the translation in each variant
968 * @param string $text the text between -{ and }-
969 * @param object $converter a LanguageConverter object
972 function __construct( $text, $converter ) {
973 $this->mText
= $text;
974 $this->mConverter
= $converter;
975 foreach ( $converter->mVariants
as $v ) {
976 $this->mConvTable
[$v] = array();
981 * Check if variants array in convert array.
983 * @param string $variant Variant language code
984 * @return string Translated text
987 function getTextInBidtable( $variants ) {
988 if ( is_string( $variants ) ) {
989 $variants = array( $variants );
991 if ( !is_array( $variants ) ) {
994 foreach ( $variants as $variant ) {
995 if ( array_key_exists( $variant, $this->mBidtable
) ) {
996 return $this->mBidtable
[$variant];
1003 * Parse flags with syntax -{FLAG| ... }-
1006 function parseFlags() {
1007 $text = $this->mText
;
1008 if ( strlen( $text ) < 2 ) {
1009 $this->mFlags
= array( 'R' );
1010 $this->mRules
= $text;
1015 $markup = $this->mConverter
->mMarkup
;
1016 $validFlags = $this->mConverter
->mFlags
;
1017 $variants = $this->mConverter
->mVariants
;
1019 $tt = explode( $markup['flagsep'], $text, 2 );
1020 if ( count( $tt ) == 2 ) {
1021 $f = explode( $markup['varsep'], $tt[0] );
1022 foreach ( $f as $ff ) {
1024 if ( array_key_exists( $ff, $validFlags )
1025 && !in_array( $validFlags[$ff], $flags ) ) {
1026 $flags[] = $validFlags[$ff];
1035 if ( in_array( 'R', $flags ) ) {
1036 $flags = array( 'R' );// remove other flags
1037 } elseif ( in_array( 'N', $flags ) ) {
1038 $flags = array( 'N' );// remove other flags
1039 } elseif ( in_array( '-', $flags ) ) {
1040 $flags = array( '-' );// remove other flags
1041 } elseif ( count( $flags ) == 1 && $flags[0] == 'T' ) {
1043 } elseif ( in_array( 'H', $flags ) ) {
1044 // replace A flag, and remove other flags except T
1045 $temp = array( '+', 'H' );
1046 if ( in_array( 'T', $flags ) ) {
1049 if ( in_array( 'D', $flags ) ) {
1054 if ( in_array( 'A', $flags ) ) {
1058 if ( in_array( 'D', $flags ) ) {
1059 $flags = array_diff( $flags, array( 'S' ) );
1061 $flags_temp = array();
1062 foreach ( $variants as $variant ) {
1063 // try to find flags like "zh-hans", "zh-hant"
1064 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1065 if ( in_array( $variant, $flags ) )
1066 $flags_temp[] = $variant;
1068 if ( count( $flags_temp ) !== 0 ) {
1069 $flags = $flags_temp;
1072 if ( count( $flags ) == 0 ) {
1073 $flags = array( 'S' );
1075 $this->mRules
= $rules;
1076 $this->mFlags
= $flags;
1080 * Generate conversion table.
1083 function parseRules() {
1084 $rules = $this->mRules
;
1085 $flags = $this->mFlags
;
1086 $bidtable = array();
1087 $unidtable = array();
1088 $markup = $this->mConverter
->mMarkup
;
1089 $variants = $this->mConverter
->mVariants
;
1091 // varsep_pattern for preg_split:
1092 // text should be splited by ";" only if a valid variant
1093 // name exist after the markup, for example:
1094 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1095 // <span style="font-size:120%;">yyy</span>;}-
1096 // we should split it as:
1098 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1099 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1102 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1103 foreach ( $variants as $variant ) {
1104 // zh-hans:xxx;zh-hant:yyy
1105 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|';
1106 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1107 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1108 . '\s*' . $markup['codesep'] . '|';
1110 $varsep_pattern .= '\s*$)/';
1112 $choice = preg_split( $varsep_pattern, $rules );
1114 foreach ( $choice as $c ) {
1115 $v = explode( $markup['codesep'], $c, 2 );
1116 if ( count( $v ) != 2 ) {
1117 // syntax error, skip
1120 $to = trim( $v[1] );
1122 $u = explode( $markup['unidsep'], $v, 2 );
1123 // if $to is empty, strtr() could return a wrong result
1124 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1125 $bidtable[$v] = $to;
1126 } elseif ( count( $u ) == 2 ) {
1127 $from = trim( $u[0] );
1129 if ( array_key_exists( $v, $unidtable )
1130 && !is_array( $unidtable[$v] )
1132 && in_array( $v, $variants ) ) {
1133 $unidtable[$v] = array( $from => $to );
1134 } elseif ( $to && in_array( $v, $variants ) ) {
1135 $unidtable[$v][$from] = $to;
1138 // syntax error, pass
1139 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ) {
1140 $bidtable = array();
1141 $unidtable = array();
1145 $this->mBidtable
= $bidtable;
1146 $this->mUnidtable
= $unidtable;
1152 function getRulesDesc() {
1153 $codesep = $this->mConverter
->mDescCodeSep
;
1154 $varsep = $this->mConverter
->mDescVarSep
;
1156 foreach ( $this->mBidtable
as $k => $v ) {
1157 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1159 foreach ( $this->mUnidtable
as $k => $a ) {
1160 foreach ( $a as $from => $to ) {
1161 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1162 "$codesep$to$varsep";
1169 * Parse rules conversion.
1172 function getRuleConvertedStr( $variant, $doConvert ) {
1173 $bidtable = $this->mBidtable
;
1174 $unidtable = $this->mUnidtable
;
1176 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1177 return $this->mRules
;
1178 } elseif ( $doConvert ) { // the text converted
1179 // display current variant in bidirectional array
1180 $disp = $this->getTextInBidtable( $variant );
1181 // or display current variant in fallbacks
1183 $disp = $this->getTextInBidtable(
1184 $this->mConverter
->getVariantFallbacks( $variant ) );
1186 // or display current variant in unidirectional array
1187 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1188 $disp = array_values( $unidtable[$variant] );
1191 // or display frist text under disable manual convert
1193 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1194 if ( count( $bidtable ) > 0 ) {
1195 $disp = array_values( $bidtable );
1198 $disp = array_values( $unidtable );
1199 $disp = array_values( $disp[0] );
1204 } else { // no convert
1205 return $this->mRules
;
1210 * Generate conversion table for all text.
1213 function generateConvTable() {
1214 $flags = $this->mFlags
;
1215 $bidtable = $this->mBidtable
;
1216 $unidtable = $this->mUnidtable
;
1217 $manLevel = $this->mConverter
->mManualLevel
;
1220 foreach ( $this->mConverter
->mVariants
as $v ) {
1221 /* for bidirectional array
1222 fill in the missing variants, if any,
1224 if ( !array_key_exists( $v, $bidtable ) ) {
1226 $this->mConverter
->getVariantFallbacks( $v );
1227 $vf = $this->getTextInBidtable( $variantFallbacks );
1229 $bidtable[$v] = $vf;
1233 if ( array_key_exists( $v, $bidtable ) ) {
1234 foreach ( $vmarked as $vo ) {
1235 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1236 // or -{H|zh:WordZh;zh-tw:WordTw}-
1237 // or -{-|zh:WordZh;zh-tw:WordTw}-
1238 // to introduce a custom mapping between
1239 // words WordZh and WordTw in the whole text
1240 if ( $manLevel[$v] == 'bidirectional' ) {
1241 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1243 if ( $manLevel[$vo] == 'bidirectional' ) {
1244 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1249 /*for unidirectional array fill to convert tables */
1250 if ( ( $manLevel[$v] == 'bidirectional'
1251 ||
$manLevel[$v] == 'unidirectional' )
1252 && array_key_exists( $v, $unidtable ) ) {
1253 $ct = $this->mConvTable
[$v];
1254 $this->mConvTable
[$v] = array_merge( $ct, $unidtable[$v] );
1260 * Parse rules and flags.
1263 function parse( $variant = NULL ) {
1265 $variant = $this->mConverter
->getPreferredVariant();
1268 $variants = $this->mConverter
->mVariants
;
1269 $this->parseFlags();
1270 $flags = $this->mFlags
;
1272 // convert to specified variant
1273 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1274 if ( count( array_diff( $flags, $variants ) ) == 0
1275 and count( $flags ) != 0 ) {
1276 // check if current variant in flags
1277 if ( in_array( $variant, $flags ) ) {
1278 // then convert <text to convert> to current language
1279 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1281 } else { // if current variant no in flags,
1282 // then we check its fallback variants.
1284 $this->mConverter
->getVariantFallbacks( $variant );
1285 foreach ( $variantFallbacks as $variantFallback ) {
1286 // if current variant's fallback exist in flags
1287 if ( in_array( $variantFallback, $flags ) ) {
1288 // then convert <text to convert> to fallback language
1290 $this->mConverter
->autoConvert( $this->mRules
,
1296 $this->mFlags
= $flags = array( 'R' );
1299 if ( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1300 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1301 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1303 $this->parseRules();
1305 $rules = $this->mRules
;
1307 if ( count( $this->mBidtable
) == 0
1308 && count( $this->mUnidtable
) == 0 ) {
1309 if ( in_array( '+', $flags ) ||
in_array( '-', $flags ) ) {
1310 // fill all variants if text in -{A/H/-|text} without rules
1311 foreach ( $this->mConverter
->mVariants
as $v ) {
1312 $this->mBidtable
[$v] = $rules;
1314 } elseif ( !in_array( 'N', $flags ) && !in_array( 'T', $flags ) ) {
1315 $this->mFlags
= $flags = array( 'R' );
1319 if ( in_array( 'R', $flags ) ) {
1320 // if we don't do content convert, still strip the -{}- tags
1321 $this->mRuleDisplay
= $rules;
1322 } elseif ( in_array( 'N', $flags ) ) {
1323 // proces N flag: output current variant name
1324 $this->mRuleDisplay
=
1325 $this->mConverter
->mVariantNames
[ trim( $rules ) ];
1326 } elseif ( in_array( 'D', $flags ) ) {
1327 // proces D flag: output rules description
1328 $this->mRuleDisplay
= $this->getRulesDesc();
1329 } elseif ( in_array( 'H', $flags ) ||
in_array( '-', $flags ) ) {
1330 // proces H,- flag or T only: output nothing
1331 $this->mRuleDisplay
= '';
1332 } elseif ( in_array( 'S', $flags ) ) {
1333 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant,
1334 $this->mConverter
->mDoContentConvert
);
1336 $this->mRuleDisplay
= $this->mManualCodeError
;
1339 if ( in_array( 'T', $flags ) ) {
1340 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant,
1341 $this->mConverter
->mDoTitleConvert
);
1344 if ( in_array( '-', $flags ) ) {
1345 $this->mRulesAction
= 'remove';
1347 if ( in_array( '+', $flags ) ) {
1348 $this->mRulesAction
= 'add';
1351 $this->generateConvTable();
1357 function hasRules() {
1362 * Get display text on markup -{...}-
1365 function getDisplay() {
1366 return $this->mRuleDisplay
;
1370 * Get converted title.
1373 function getTitle() {
1374 return $this->mRuleTitle
;
1378 * Return how deal with conversion rules.
1381 function getRulesAction() {
1382 return $this->mRulesAction
;
1386 * Get conversion table. ( bidirectional and unidirectional
1387 * conversion table )
1390 function getConvTable() {
1391 return $this->mConvTable
;
1395 * Get conversion rules string.
1398 function getRules() {
1399 return $this->mRules
;
1403 * Get conversion flags.
1406 function getFlags() {
1407 return $this->mFlags
;