4 * Contains the LanguageConverter class and ConverterRule class
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
12 * Base class for language conversion.
15 * @author Zhengzhu Feng <zhengzhu@gmail.com>
16 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>, PhiLiP <philip.npc@gmail.com>
18 class LanguageConverter
{
19 var $mMainLanguageCode;
20 var $mVariants, $mVariantFallbacks, $mVariantNames;
21 var $mTablesLoaded = false;
23 // 'bidirectional' 'unidirectional' 'disable' for each variant
28 var $mDescCodeSep = ':', $mDescVarSep = ';';
29 var $mUcfirst = false;
30 var $mConvRuleTitle = false;
35 var $mVarSeparatorPattern;
37 const CACHE_VERSION_KEY
= 'VERSION 6';
42 * @param $langobj The Language Object
43 * @param $maincode String: the main language code of this language
44 * @param $variants Array: the supported variants of this language
45 * @param $variantfallbacks Array: the fallback language of each variant
46 * @param $flags Array: defining the custom strings that maps to the flags
47 * @param $manualLevel Array: limit for supported variants
49 public function __construct( $langobj, $maincode,
51 $variantfallbacks = array(),
53 $manualLevel = array() ) {
54 $this->mLangObj
= $langobj;
55 $this->mMainLanguageCode
= $maincode;
57 global $wgDisabledVariants;
58 $this->mVariants
= array();
59 foreach ( $variants as $variant ) {
60 if ( !in_array( $variant, $wgDisabledVariants ) ) {
61 $this->mVariants
[] = $variant;
64 $this->mVariantFallbacks
= $variantfallbacks;
65 global $wgLanguageNames;
66 $this->mVariantNames
= $wgLanguageNames;
67 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
69 // 'S' show converted text
70 // '+' add rules for alltext
71 // 'E' the gave flags is error
72 // these flags above are reserved for program
73 'A' => 'A', // add rule for convert code (all text convert)
74 'T' => 'T', // title convert
75 'R' => 'R', // raw content
76 'D' => 'D', // convert description (subclass implement)
77 '-' => '-', // remove convert (not implement)
78 'H' => 'H', // add rule for convert code
79 // (but no display in placed code )
80 'N' => 'N' // current variant name
82 $this->mFlags
= array_merge( $f, $flags );
83 foreach ( $this->mVariants
as $v ) {
84 if ( array_key_exists( $v, $manualLevel ) ) {
85 $this->mManualLevel
[$v] = $manualLevel[$v];
87 $this->mManualLevel
[$v] = 'bidirectional';
89 $this->mFlags
[$v] = $v;
96 function getVariants() {
97 return $this->mVariants
;
101 * In case some variant is not defined in the markup, we need
102 * to have some fallback. For example, in zh, normally people
103 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
104 * when zh-sg is preferred but not defined, we will pick zh-hans
105 * in this case. Right now this is only used by zh.
107 * @param $v String: the language code of the variant
108 * @return string array The code of the fallback language or false if there
111 public function getVariantFallbacks( $v ) {
112 if ( isset( $this->mVariantFallbacks
[$v] ) ) {
113 return $this->mVariantFallbacks
[$v];
115 return $this->mMainLanguageCode
;
119 * Get the title produced by the conversion rule.
122 function getConvRuleTitle() {
123 return $this->mConvRuleTitle
;
127 * Get preferred language variants.
128 * @param $fromUser Boolean: get it from $wgUser's preferences
129 * @param $fromHeader Boolean: get it from Accept-Language
130 * @return String: the preferred language code
132 public function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
133 global $wgDefaultLanguageVariant;
135 $req = $this->getURLVariant();
137 if ( $fromUser && !$req ) {
138 $req = $this->getUserVariant();
141 if ( $fromHeader && !$req ) {
142 $req = $this->getHeaderVariant();
145 if ( $wgDefaultLanguageVariant && !$req ) {
146 $req = $this->validateVariant( $wgDefaultLanguageVariant );
149 // This function, unlike the other get*Variant functions, is
150 // not memoized (i.e. there return value is not cached) since
151 // new information might appear during processing after this
156 return $this->mMainLanguageCode
;
160 * Validate the variant
161 * @param $v String: the variant to validate
162 * @return Mixed: returns the variant if it is valid, null otherwise
164 function validateVariant( $v = null ) {
165 if ( $v !== null && in_array( $v, $this->mVariants
) ) {
172 * Get the variant specified in the URL
174 * @return Mixed: variant if one found, false otherwise.
176 function getURLVariant() {
180 if ( $this->mURLVariant
) {
181 return $this->mURLVariant
;
184 // see if the preference is set in the request
185 $ret = $wgRequest->getText( 'variant' );
188 $ret = $wgRequest->getVal( 'uselang' );
191 return $this->mURLVariant
= $this->validateVariant( $ret );
195 * Determine if the user has a variant set.
197 * @return Mixed: variant if one found, false otherwise.
199 function getUserVariant() {
203 // memoizing this function wreaks havoc on parserTest.php
204 /* if ( $this->mUserVariant ) { */
205 /* return $this->mUserVariant; */
208 // get language variant preference from logged in users
209 // Don't call this on stub objects because that causes infinite
210 // recursion during initialisation
211 if ( $wgUser->isLoggedIn() ) {
212 $ret = $wgUser->getOption( 'variant' );
215 // figure out user lang without constructing wgLang to avoid
216 // infinite recursion
217 $ret = $wgUser->getOption( 'language' );
220 return $this->mUserVariant
= $this->validateVariant( $ret );
225 * Determine the language variant from the Accept-Language header.
227 * @return Mixed: variant if one found, false otherwise.
229 function getHeaderVariant() {
233 if ( $this->mHeaderVariant
) {
234 return $this->mHeaderVariant
;
237 // see if some supported language variant is set in the
240 $acceptLanguage = $wgRequest->getHeader( 'Accept-Language' );
241 if ( !$acceptLanguage ) {
246 $result = StringUtils
::explode( ',', strtolower( $acceptLanguage ) );
247 $languages = array();
249 foreach ( $result as $elem ) {
250 // if $elem likes 'zh-cn;q=0.9'
251 if ( ( $posi = strpos( $elem, ';' ) ) !== false ) {
252 // get the real language code likes 'zh-cn'
253 $languages[] = substr( $elem, 0, $posi );
255 $languages[] = $elem;
259 $fallback_languages = array();
260 foreach ( $languages as $language ) {
262 $language = trim( $language );
263 $this->mHeaderVariant
= $this->validateVariant( $language );
264 if ( $this->mHeaderVariant
) {
268 // To see if there are fallbacks of current language.
269 // We record these fallback variants, and process
271 $fallbacks = $this->getVariantFallbacks( $language );
272 if ( is_string( $fallbacks ) ) {
273 $fallback_languages[] = $fallbacks;
274 } elseif ( is_array( $fallbacks ) ) {
275 $fallback_languages =
276 array_merge( $fallback_languages,
281 if ( !$this->mHeaderVariant
) {
282 // process fallback languages now
283 $fallback_languages = array_unique( $fallback_languages );
284 foreach ( $fallback_languages as $language ) {
285 $this->mHeaderVariant
= $this->validateVariant( $language );
286 if ( $this->mHeaderVariant
) {
292 return $this->mHeaderVariant
;
296 * Caption convert, base on preg_replace_callback.
298 * To convert text in "title" or "alt", like '<img alt="text" ... '
299 * or '<span title="text" ... '
301 * @return String like ' alt="yyyy"' or ' title="yyyy"'
304 function captionConvert( $matches ) {
305 $toVariant = $this->getPreferredVariant();
306 $title = $matches[1];
308 // we convert captions except URL
309 if ( !strpos( $text, '://' ) ) {
310 $text = $this->translate( $text, $toVariant );
312 return " $title=\"$text\"";
316 * Dictionary-based conversion.
318 * @param $text String: the text to be converted
319 * @param $toVariant String: the target language code
320 * @return String: the converted text
323 function autoConvert( $text, $toVariant = false ) {
324 $fname = 'LanguageConverter::autoConvert';
326 wfProfileIn( $fname );
328 if ( !$this->mTablesLoaded
) {
333 $toVariant = $this->getPreferredVariant();
339 /* we convert everything except:
340 1. html markups (anything between < and >)
342 3. place holders created by the parser
345 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
346 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
351 // this one is needed when the text is inside an html markup
352 $htmlfix = '|<[^>]+$|^[^<>]*>';
354 // disable convert to variants between <code></code> tags
355 $codefix = '<code>.+?<\/code>|';
356 // disable convertsion of <script type="text/javascript"> ... </script>
357 $scriptfix = '<script.*?>.*?<\/script>|';
358 // disable conversion of <pre xxxx> ... </pre>
359 $prefix = '<pre.*?>.*?<\/pre>|';
361 $reg = '/' . $codefix . $scriptfix . $prefix .
362 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
364 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
366 $m = array_shift( $matches );
368 $ret = $this->translate( $m[0], $toVariant );
369 $mstart = $m[1] +
strlen( $m[0] );
371 // enable convertsion of '<img alt="xxxx" ... '
372 // or '<span title="xxxx" ... '
373 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
378 foreach ( $matches as $m ) {
379 $mark = substr( $text, $mstart, $m[1] - $mstart );
380 $mark = preg_replace_callback( $captionpattern,
381 array( &$this, 'captionConvert' ),
383 // Let's convert the trtext only once,
384 // it would give us more performance improvement
386 $trtext .= $m[0] . $trtextmark;
387 $mstart = $m[1] +
strlen( $m[0] );
390 $trtext = $this->translate( $trtext, $toVariant );
391 $trtext = StringUtils
::explode( $trtextmark, $trtext );
392 foreach ( $trtext as $t ) {
393 $ret .= array_shift( $notrtext );
396 wfProfileOut( $fname );
401 * Translate a string to a variant.
402 * Doesn't process markup or do any of that other stuff, for that use
405 * @param $text String: text to convert
406 * @param $variant String: variant language code
407 * @return String: translated text
410 function translate( $text, $variant ) {
411 wfProfileIn( __METHOD__
);
412 // If $text is empty or only includes spaces, do nothing
413 // Otherwise translate it
414 if ( trim( $text ) ) {
415 if ( !$this->mTablesLoaded
) {
418 $text = $this->mTables
[$variant]->replace( $text );
420 wfProfileOut( __METHOD__
);
425 * Convert text to all supported variants.
427 * @param $text String: the text to be converted
428 * @return Array of string
430 public function autoConvertToAllVariants( $text ) {
431 $fname = 'LanguageConverter::autoConvertToAllVariants';
432 wfProfileIn( $fname );
433 if ( !$this->mTablesLoaded
) {
438 foreach ( $this->mVariants
as $variant ) {
439 $ret[$variant] = $this->translate( $text, $variant );
442 wfProfileOut( $fname );
447 * Convert link text to all supported variants.
449 * @param $text String: the text to be converted
450 * @return Array of string
452 public function convertLinkToAllVariants( $text ) {
453 if ( !$this->mTablesLoaded
) {
458 $tarray = StringUtils
::explode( '-{', $text );
461 foreach ( $tarray as $txt ) {
464 foreach ( $this->mVariants
as $variant ) {
465 $ret[$variant] = $this->translate( $txt, $variant );
470 $marked = explode( '}-', $txt, 2 );
472 foreach ( $this->mVariants
as $variant ) {
473 $ret[$variant] .= '-{' . $marked[0] . '}-';
474 if ( array_key_exists( 1, $marked ) ) {
475 $ret[$variant] .= $this->translate( $marked[1], $variant );
485 * Prepare manual conversion table.
488 function applyManualConv( $convRule ) {
489 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
491 // Bug 24072: mConvRuleTitle won't work if the title conversion
492 // rule was followed by other manual conversion rule(s).
493 $newConvRuleTitle = $convRule->getTitle();
494 if( $newConvRuleTitle ) {
495 $this->mConvRuleTitle
= $newConvRuleTitle;
498 // apply manual conversion table to global table
499 $convTable = $convRule->getConvTable();
500 $action = $convRule->getRulesAction();
501 foreach ( $convTable as $variant => $pair ) {
502 if ( !$this->validateVariant( $variant ) ) {
506 if ( $action == 'add' ) {
507 foreach ( $pair as $from => $to ) {
508 // to ensure that $from and $to not be left blank
509 // so $this->translate() could always return a string
510 if ( $from ||
$to ) {
511 // more efficient than array_merge(), about 2.5 times.
512 $this->mTables
[$variant]->setPair( $from, $to );
515 } elseif ( $action == 'remove' ) {
516 $this->mTables
[$variant]->removeArray( $pair );
522 * Convert text to different variants of a language. The automatic
523 * conversion is done in autoConvert(). Here we parse the text
524 * marked with -{}-, which specifies special conversions of the
525 * text that can not be accomplished in autoConvert().
527 * Syntax of the markup:
528 * -{code1:text1;code2:text2;...}- or
529 * -{flags|code1:text1;code2:text2;...}- or
530 * -{text}- in which case no conversion should take place for text
532 * @param $text String: text to be converted
533 * @return String: converted text
535 public function convert( $text ) {
536 global $wgDisableLangConversion;
537 if ( $wgDisableLangConversion ) return $text;
539 $variant = $this->getPreferredVariant();
541 return $this->recursiveConvertTopLevel( $text, $variant );
545 * Convert a Title object to a readable string in the preferred variant
547 public function convertTitle( $title ) {
548 $variant = $this->getPreferredVariant();
549 $index = $title->getNamespace();
550 if ( $index === NS_MAIN
) {
553 // first let's check if a message has given us a converted name
554 $nsConvKey = 'conversion-ns' . $index;
555 if ( !wfEmptyMsg( $nsConvKey ) ) {
556 $text = wfMsgForContentNoTrans( $nsConvKey );
558 // the message does not exist, try retrieve it from the current
559 // variant's namespace names.
560 $langObj = $this->mLangObj
->factory( $variant );
561 $text = $langObj->getFormattedNsText( $index );
565 $text .= $title->getText();
566 $text = $this->autoConvert( $text, $variant );
570 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
573 $length = strlen( $text );
574 while ( $startPos < $length ) {
576 $pos = strpos( $text, '-{', $startPos );
578 if ( $pos === false ) {
579 // No more markup, append final segment
580 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
586 // Append initial segment
587 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
592 // Do recursive conversion
593 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
599 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
600 // Quick sanity check (no function calls)
601 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
602 throw new MWException( __METHOD__
.': invalid input string' );
607 $warningDone = false;
608 $length = strlen( $text );
610 while ( $startPos < $length ) {
612 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
622 // Append initial segment
623 $inner .= substr( $text, $startPos, $pos - $startPos );
631 if ( $depth >= $this->mMaxDepth
) {
633 if ( !$warningDone ) {
634 $inner .= '<span class="error">' .
635 wfMsgForContent( 'language-converter-depth-warning',
643 // Recursively parse another rule
644 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
649 $rule = new ConverterRule( $inner, $this );
650 $rule->parse( $variant );
651 $this->applyManualConv( $rule );
652 return $rule->getDisplay();
654 throw new MWException( __METHOD__
.': invalid regex match' );
659 if ( $startPos < $length ) {
660 $inner .= substr( $text, $startPos );
663 return '-{' . $this->autoConvert( $inner, $variant );
667 * If a language supports multiple variants, it is
668 * possible that non-existing link in one variant
669 * actually exists in another variant. This function
670 * tries to find it. See e.g. LanguageZh.php
672 * @param $link String: the name of the link
673 * @param $nt Mixed: the title object of the link
674 * @param $ignoreOtherCond Boolean: to disable other conditions when
675 * we need to transclude a template or update a category's link
676 * @return Null, the input parameters may be modified upon return
678 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
679 # If the article has already existed, there is no need to
680 # check it again, otherwise it may cause a fault.
681 if ( is_object( $nt ) && $nt->exists() ) {
685 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
687 $isredir = $wgRequest->getText( 'redirect', 'yes' );
688 $action = $wgRequest->getText( 'action' );
689 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
690 $disableLinkConversion = $wgDisableLangConversion
691 ||
$wgDisableTitleConversion;
692 $linkBatch = new LinkBatch();
696 if ( $disableLinkConversion ||
697 ( !$ignoreOtherCond &&
700 ||
$action == 'submit'
701 ||
$linkconvert == 'no'
702 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
706 if ( is_object( $nt ) ) {
707 $ns = $nt->getNamespace();
710 $variants = $this->autoConvertToAllVariants( $link );
711 if ( !$variants ) { // give up
717 foreach ( $variants as $v ) {
719 $varnt = Title
::newFromText( $v, $ns );
720 if ( !is_null( $varnt ) ) {
721 $linkBatch->addObj( $varnt );
727 // fetch all variants in single query
728 $linkBatch->execute();
730 foreach ( $titles as $varnt ) {
731 if ( $varnt->getArticleID() > 0 ) {
733 $link = $varnt->getText();
740 * Returns language specific hash options.
742 public function getExtraHashOptions() {
743 $variant = $this->getPreferredVariant();
744 return '!' . $variant ;
748 * Load default conversion tables.
749 * This method must be implemented in derived class.
753 function loadDefaultTables() {
754 $name = get_class( $this );
755 wfDie( "Must implement loadDefaultTables() method in class $name" );
759 * Load conversion tables either from the cache or the disk.
762 function loadTables( $fromcache = true ) {
764 if ( $this->mTablesLoaded
) {
767 wfProfileIn( __METHOD__
);
768 $this->mTablesLoaded
= true;
769 $this->mTables
= false;
771 wfProfileIn( __METHOD__
. '-cache' );
772 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
773 wfProfileOut( __METHOD__
. '-cache' );
776 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
777 wfProfileIn( __METHOD__
. '-recache' );
778 // not in cache, or we need a fresh reload.
779 // we will first load the default tables
780 // then update them using things in MediaWiki:Zhconversiontable/*
781 $this->loadDefaultTables();
782 foreach ( $this->mVariants
as $var ) {
783 $cached = $this->parseCachedTable( $var );
784 $this->mTables
[$var]->mergeArray( $cached );
787 $this->postLoadTables();
788 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
790 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
791 wfProfileOut( __METHOD__
. '-recache' );
793 wfProfileOut( __METHOD__
);
797 * Hook for post processig after conversion tables are loaded.
800 function postLoadTables() { }
803 * Reload the conversion tables.
807 function reloadTables() {
808 if ( $this->mTables
) {
809 unset( $this->mTables
);
811 $this->mTablesLoaded
= false;
812 $this->loadTables( false );
817 * Parse the conversion table stored in the cache.
819 * The tables should be in blocks of the following form:
826 * To make the tables more manageable, subpages are allowed
827 * and will be parsed recursively if $recursive == true.
830 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
831 global $wgMessageCache;
832 static $parsed = array();
834 if ( !is_object( $wgMessageCache ) ) {
838 $key = 'Conversiontable/' . $code;
840 $key .= '/' . $subpage;
842 if ( array_key_exists( $key, $parsed ) ) {
846 if ( strpos( $code, '/' ) === false ) {
847 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
848 if( $txt === false ){
849 # FIXME: this method doesn't seem to be expecting
850 # this possible outcome...
851 $txt = '<Conversiontable>';
854 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
855 "Conversiontable/$code" );
856 if ( $title && $title->exists() ) {
857 $article = new Article( $title );
858 $txt = $article->getContents();
864 // get all subpage links of the form
865 // [[MediaWiki:conversiontable/zh-xx/...|...]]
866 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
868 $subs = StringUtils
::explode( '[[', $txt );
870 foreach ( $subs as $sub ) {
871 $link = explode( ']]', $sub, 2 );
872 if ( count( $link ) != 2 ) {
875 $b = explode( '|', $link[0], 2 );
876 $b = explode( '/', trim( $b[0] ), 3 );
877 if ( count( $b ) == 3 ) {
883 if ( $b[0] == $linkhead && $b[1] == $code ) {
884 $sublinks[] = $sublink;
889 // parse the mappings in this page
890 $blocks = StringUtils
::explode( '-{', $txt );
893 foreach ( $blocks as $block ) {
895 // Skip the part before the first -{
899 $mappings = explode( '}-', $block, 2 );
900 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
902 $table = StringUtils
::explode( ';', $stripped );
903 foreach ( $table as $t ) {
904 $m = explode( '=>', $t, 3 );
905 if ( count( $m ) != 2 )
907 // trim any trailling comments starting with '//'
908 $tt = explode( '//', $m[1], 2 );
909 $ret[trim( $m[0] )] = trim( $tt[0] );
912 $parsed[$key] = true;
915 // recursively parse the subpages
917 foreach ( $sublinks as $link ) {
918 $s = $this->parseCachedTable( $code, $link, $recursive );
919 $ret = array_merge( $ret, $s );
923 if ( $this->mUcfirst
) {
924 foreach ( $ret as $k => $v ) {
925 $ret[Language
::ucfirst( $k )] = Language
::ucfirst( $v );
932 * Enclose a string with the "no conversion" tag. This is used by
933 * various functions in the Parser.
935 * @param $text String: text to be tagged for no conversion
936 * @param $noParse Unused (?)
937 * @return String: the tagged text
939 public function markNoConversion( $text, $noParse = false ) {
940 # don't mark if already marked
941 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
945 $ret = "-{R|$text}-";
950 * Convert the sorting key for category links. This should make different
951 * keys that are variants of each other map to the same key.
953 function convertCategoryKey( $key ) {
958 * Hook to refresh the cache of conversion tables when
959 * MediaWiki:conversiontable* is updated.
962 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
963 $iswatch, $section, $flags, $revision ) {
964 $titleobj = $article->getTitle();
965 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
966 $title = $titleobj->getDBkey();
967 $t = explode( '/', $title, 3 );
969 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
970 if ( $this->validateVariant( $t[1] ) ) {
971 $this->reloadTables();
979 * Armour rendered math against conversion.
980 * Wrap math into rawoutput -{R| math }- syntax.
982 public function armourMath( $text ) {
983 // we need to convert '-{' and '}-' to '-{' and '}-'
984 // to avoid a unwanted '}-' appeared after the math-image.
985 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
986 $ret = "-{R|$text}-";
991 * Get the cached separator pattern for ConverterRule::parseRules()
993 function getVarSeparatorPattern() {
994 if ( is_null( $this->mVarSeparatorPattern
) ) {
995 // varsep_pattern for preg_split:
996 // text should be splited by ";" only if a valid variant
997 // name exist after the markup, for example:
998 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
999 // <span style="font-size:120%;">yyy</span>;}-
1000 // we should split it as:
1002 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1003 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1007 foreach ( $this->mVariants
as $variant ) {
1008 // zh-hans:xxx;zh-hant:yyy
1009 $pat .= $variant . '\s*:|';
1010 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1011 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1014 $this->mVarSeparatorPattern
= $pat;
1016 return $this->mVarSeparatorPattern
;
1021 * Parser for rules of language conversion , parse rules in -{ }- tag.
1023 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1025 class ConverterRule
{
1026 var $mText; // original text in -{text}-
1027 var $mConverter; // LanguageConverter object
1028 var $mManualCodeError = '<strong class="error">code error!</strong>';
1029 var $mRuleDisplay = '';
1030 var $mRuleTitle = false;
1031 var $mRules = '';// string : the text of the rules
1032 var $mRulesAction = 'none';
1033 var $mFlags = array();
1034 var $mVariantFlags = array();
1035 var $mConvTable = array();
1036 var $mBidtable = array();// array of the translation in each variant
1037 var $mUnidtable = array();// array of the translation in each variant
1042 * @param $text String: the text between -{ and }-
1043 * @param $converter LanguageConverter object
1045 public function __construct( $text, $converter ) {
1046 $this->mText
= $text;
1047 $this->mConverter
= $converter;
1051 * Check if variants array in convert array.
1053 * @param $variants Array or string: variant language code
1054 * @return String: translated text
1056 public function getTextInBidtable( $variants ) {
1057 $variants = (array)$variants;
1061 foreach ( $variants as $variant ) {
1062 if ( isset( $this->mBidtable
[$variant] ) ) {
1063 return $this->mBidtable
[$variant];
1070 * Parse flags with syntax -{FLAG| ... }-
1073 function parseFlags() {
1074 $text = $this->mText
;
1076 $variantFlags = array();
1078 $sepPos = strpos( $text, '|' );
1079 if ( $sepPos !== false ) {
1080 $validFlags = $this->mConverter
->mFlags
;
1081 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1082 foreach ( $f as $ff ) {
1084 if ( isset( $validFlags[$ff] ) ) {
1085 $flags[$validFlags[$ff]] = true;
1088 $text = strval( substr( $text, $sepPos +
1 ) );
1093 } elseif ( isset( $flags['R'] ) ) {
1094 $flags = array( 'R' => true );// remove other flags
1095 } elseif ( isset( $flags['N'] ) ) {
1096 $flags = array( 'N' => true );// remove other flags
1097 } elseif ( isset( $flags['-'] ) ) {
1098 $flags = array( '-' => true );// remove other flags
1099 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1101 } elseif ( isset( $flags['H'] ) ) {
1102 // replace A flag, and remove other flags except T
1103 $temp = array( '+' => true, 'H' => true );
1104 if ( isset( $flags['T'] ) ) {
1107 if ( isset( $flags['D'] ) ) {
1112 if ( isset( $flags['A'] ) ) {
1116 if ( isset( $flags['D'] ) ) {
1117 unset( $flags['S'] );
1119 // try to find flags like "zh-hans", "zh-hant"
1120 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1121 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1122 if ( $variantFlags ) {
1123 $variantFlags = array_flip( $variantFlags );
1127 $this->mVariantFlags
= $variantFlags;
1128 $this->mRules
= $text;
1129 $this->mFlags
= $flags;
1133 * Generate conversion table.
1136 function parseRules() {
1137 $rules = $this->mRules
;
1138 $flags = $this->mFlags
;
1139 $bidtable = array();
1140 $unidtable = array();
1141 $variants = $this->mConverter
->mVariants
;
1142 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1144 $choice = preg_split( $varsep_pattern, $rules );
1146 foreach ( $choice as $c ) {
1147 $v = explode( ':', $c, 2 );
1148 if ( count( $v ) != 2 ) {
1149 // syntax error, skip
1152 $to = trim( $v[1] );
1154 $u = explode( '=>', $v, 2 );
1155 // if $to is empty, strtr() could return a wrong result
1156 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1157 $bidtable[$v] = $to;
1158 } elseif ( count( $u ) == 2 ) {
1159 $from = trim( $u[0] );
1161 if ( array_key_exists( $v, $unidtable )
1162 && !is_array( $unidtable[$v] )
1164 && in_array( $v, $variants ) ) {
1165 $unidtable[$v] = array( $from => $to );
1166 } elseif ( $to && in_array( $v, $variants ) ) {
1167 $unidtable[$v][$from] = $to;
1170 // syntax error, pass
1171 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1172 $bidtable = array();
1173 $unidtable = array();
1177 $this->mBidtable
= $bidtable;
1178 $this->mUnidtable
= $unidtable;
1184 function getRulesDesc() {
1185 $codesep = $this->mConverter
->mDescCodeSep
;
1186 $varsep = $this->mConverter
->mDescVarSep
;
1188 foreach ( $this->mBidtable
as $k => $v ) {
1189 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1191 foreach ( $this->mUnidtable
as $k => $a ) {
1192 foreach ( $a as $from => $to ) {
1193 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1194 "$codesep$to$varsep";
1201 * Parse rules conversion.
1204 function getRuleConvertedStr( $variant ) {
1205 $bidtable = $this->mBidtable
;
1206 $unidtable = $this->mUnidtable
;
1208 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1209 return $this->mRules
;
1211 // display current variant in bidirectional array
1212 $disp = $this->getTextInBidtable( $variant );
1213 // or display current variant in fallbacks
1215 $disp = $this->getTextInBidtable(
1216 $this->mConverter
->getVariantFallbacks( $variant ) );
1218 // or display current variant in unidirectional array
1219 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1220 $disp = array_values( $unidtable[$variant] );
1223 // or display frist text under disable manual convert
1225 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1226 if ( count( $bidtable ) > 0 ) {
1227 $disp = array_values( $bidtable );
1230 $disp = array_values( $unidtable );
1231 $disp = array_values( $disp[0] );
1240 * Generate conversion table for all text.
1243 function generateConvTable() {
1244 // Special case optimisation
1245 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1246 $this->mConvTable
= array();
1250 $bidtable = $this->mBidtable
;
1251 $unidtable = $this->mUnidtable
;
1252 $manLevel = $this->mConverter
->mManualLevel
;
1255 foreach ( $this->mConverter
->mVariants
as $v ) {
1256 /* for bidirectional array
1257 fill in the missing variants, if any,
1259 if ( !isset( $bidtable[$v] ) ) {
1261 $this->mConverter
->getVariantFallbacks( $v );
1262 $vf = $this->getTextInBidtable( $variantFallbacks );
1264 $bidtable[$v] = $vf;
1268 if ( isset( $bidtable[$v] ) ) {
1269 foreach ( $vmarked as $vo ) {
1270 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1271 // or -{H|zh:WordZh;zh-tw:WordTw}-
1272 // or -{-|zh:WordZh;zh-tw:WordTw}-
1273 // to introduce a custom mapping between
1274 // words WordZh and WordTw in the whole text
1275 if ( $manLevel[$v] == 'bidirectional' ) {
1276 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1278 if ( $manLevel[$vo] == 'bidirectional' ) {
1279 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1284 /*for unidirectional array fill to convert tables */
1285 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1286 && isset( $unidtable[$v] ) )
1288 if ( isset( $this->mConvTable
[$v] ) ) {
1289 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1291 $this->mConvTable
[$v] = $unidtable[$v];
1298 * Parse rules and flags.
1301 function parse( $variant = NULL ) {
1303 $variant = $this->mConverter
->getPreferredVariant();
1306 $variants = $this->mConverter
->mVariants
;
1307 $this->parseFlags();
1308 $flags = $this->mFlags
;
1310 // convert to specified variant
1311 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1312 if ( $this->mVariantFlags
) {
1313 // check if current variant in flags
1314 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1315 // then convert <text to convert> to current language
1316 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1318 } else { // if current variant no in flags,
1319 // then we check its fallback variants.
1321 $this->mConverter
->getVariantFallbacks( $variant );
1322 foreach ( $variantFallbacks as $variantFallback ) {
1323 // if current variant's fallback exist in flags
1324 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1325 // then convert <text to convert> to fallback language
1327 $this->mConverter
->autoConvert( $this->mRules
,
1333 $this->mFlags
= $flags = array( 'R' => true );
1336 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1337 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1338 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1339 $this->parseRules();
1341 $rules = $this->mRules
;
1343 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1344 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1345 // fill all variants if text in -{A/H/-|text} without rules
1346 foreach ( $this->mConverter
->mVariants
as $v ) {
1347 $this->mBidtable
[$v] = $rules;
1349 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1350 $this->mFlags
= $flags = array( 'R' => true );
1354 $this->mRuleDisplay
= false;
1355 foreach ( $flags as $flag => $unused ) {
1358 // if we don't do content convert, still strip the -{}- tags
1359 $this->mRuleDisplay
= $rules;
1362 // process N flag: output current variant name
1363 $ruleVar = trim( $rules );
1364 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1365 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1367 $this->mRuleDisplay
= '';
1371 // process D flag: output rules description
1372 $this->mRuleDisplay
= $this->getRulesDesc();
1375 // process H,- flag or T only: output nothing
1376 $this->mRuleDisplay
= '';
1379 $this->mRulesAction
= 'remove';
1380 $this->mRuleDisplay
= '';
1383 $this->mRulesAction
= 'add';
1384 $this->mRuleDisplay
= '';
1387 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1390 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1391 $this->mRuleDisplay
= '';
1394 // ignore unknown flags (but see error case below)
1397 if ( $this->mRuleDisplay
=== false ) {
1398 $this->mRuleDisplay
= $this->mManualCodeError
;
1401 $this->generateConvTable();
1407 function hasRules() {
1412 * Get display text on markup -{...}-
1415 function getDisplay() {
1416 return $this->mRuleDisplay
;
1420 * Get converted title.
1423 function getTitle() {
1424 return $this->mRuleTitle
;
1428 * Return how deal with conversion rules.
1431 function getRulesAction() {
1432 return $this->mRulesAction
;
1436 * Get conversion table. ( bidirectional and unidirectional
1437 * conversion table )
1440 function getConvTable() {
1441 return $this->mConvTable
;
1445 * Get conversion rules string.
1448 function getRules() {
1449 return $this->mRules
;
1453 * Get conversion flags.
1456 function getFlags() {
1457 return $this->mFlags
;