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 global $wgDisabledVariants, $wgLanguageNames;
55 $this->mLangObj
= $langobj;
56 $this->mMainLanguageCode
= $maincode;
57 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
58 $this->mVariantFallbacks
= $variantfallbacks;
59 $this->mVariantNames
= $wgLanguageNames;
60 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
61 $defaultflags = array(
62 // 'S' show converted text
63 // '+' add rules for alltext
64 // 'E' the gave flags is error
65 // these flags above are reserved for program
66 'A' => 'A', // add rule for convert code (all text convert)
67 'T' => 'T', // title convert
68 'R' => 'R', // raw content
69 'D' => 'D', // convert description (subclass implement)
70 '-' => '-', // remove convert (not implement)
71 'H' => 'H', // add rule for convert code
72 // (but no display in placed code )
73 'N' => 'N' // current variant name
75 $this->mFlags
= array_merge( $defaultflags, $flags );
76 foreach ( $this->mVariants
as $v ) {
77 if ( array_key_exists( $v, $manualLevel ) ) {
78 $this->mManualLevel
[$v] = $manualLevel[$v];
80 $this->mManualLevel
[$v] = 'bidirectional';
82 $this->mFlags
[$v] = $v;
87 * Get all valid variants.
88 * Call this instead of using $this->mVariants directly.
90 * @return Array: contains all valid variants
92 public function getVariants() {
93 return $this->mVariants
;
97 * In case some variant is not defined in the markup, we need
98 * to have some fallback. For example, in zh, normally people
99 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
100 * when zh-sg is preferred but not defined, we will pick zh-hans
101 * in this case. Right now this is only used by zh.
103 * @param $variant String: the language code of the variant
104 * @return String: The code of the fallback language or the
105 * main code if there is no fallback
107 public function getVariantFallbacks( $variant ) {
108 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
109 return $this->mVariantFallbacks
[$variant];
111 return $this->mMainLanguageCode
;
115 * Get the title produced by the conversion rule.
116 * @return String: The converted title text
118 public function getConvRuleTitle() {
119 return $this->mConvRuleTitle
;
123 * Get preferred language variant.
124 * @param $fromUser Boolean: get it from $wgUser's preferences
125 * @param $fromHeader Boolean: get it from Accept-Language
126 * @return String: the preferred language code
128 public function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
129 global $wgDefaultLanguageVariant;
131 $req = $this->getURLVariant();
133 if ( $fromUser && !$req ) {
134 $req = $this->getUserVariant();
137 if ( $fromHeader && !$req ) {
138 $req = $this->getHeaderVariant();
141 if ( $wgDefaultLanguageVariant && !$req ) {
142 $req = $this->validateVariant( $wgDefaultLanguageVariant );
145 // This function, unlike the other get*Variant functions, is
146 // not memoized (i.e. there return value is not cached) since
147 // new information might appear during processing after this
152 return $this->mMainLanguageCode
;
156 * Validate the variant
157 * @param $variant String: the variant to validate
158 * @return Mixed: returns the variant if it is valid, null otherwise
160 protected function validateVariant( $variant = null ) {
161 if ( $variant !== null &&
162 in_array( $variant, $this->mVariants
) ) {
169 * Get the variant specified in the URL
171 * @return Mixed: variant if one found, false otherwise.
173 protected function getURLVariant() {
177 if ( $this->mURLVariant
) {
178 return $this->mURLVariant
;
181 // see if the preference is set in the request
182 $ret = $wgRequest->getText( 'variant' );
185 $ret = $wgRequest->getVal( 'uselang' );
188 return $this->mURLVariant
= $this->validateVariant( $ret );
192 * Determine if the user has a variant set.
194 * @return Mixed: variant if one found, false otherwise.
196 protected function getUserVariant() {
200 // memoizing this function wreaks havoc on parserTest.php
201 /* if ( $this->mUserVariant ) { */
202 /* return $this->mUserVariant; */
205 // get language variant preference from logged in users
206 // Don't call this on stub objects because that causes infinite
207 // recursion during initialisation
208 if ( $wgUser->isLoggedIn() ) {
209 $ret = $wgUser->getOption( 'variant' );
212 // figure out user lang without constructing wgLang to avoid
213 // infinite recursion
214 $ret = $wgUser->getOption( 'language' );
217 return $this->mUserVariant
= $this->validateVariant( $ret );
222 * Determine the language variant from the Accept-Language header.
224 * @return Mixed: variant if one found, false otherwise.
226 protected function getHeaderVariant() {
229 if ( $this->mHeaderVariant
) {
230 return $this->mHeaderVariant
;
233 // see if some supported language variant is set in the
235 $languages = array_keys( $wgRequest->getAcceptLang() );
236 if ( empty( $languages ) ) {
240 $fallback_languages = array();
241 foreach ( $languages as $language ) {
242 $this->mHeaderVariant
= $this->validateVariant( $language );
243 if ( $this->mHeaderVariant
) {
247 // To see if there are fallbacks of current language.
248 // We record these fallback variants, and process
250 $fallbacks = $this->getVariantFallbacks( $language );
251 if ( is_string( $fallbacks ) ) {
252 $fallback_languages[] = $fallbacks;
253 } elseif ( is_array( $fallbacks ) ) {
254 $fallback_languages =
255 array_merge( $fallback_languages,
260 if ( !$this->mHeaderVariant
) {
261 // process fallback languages now
262 $fallback_languages = array_unique( $fallback_languages );
263 foreach ( $fallback_languages as $language ) {
264 $this->mHeaderVariant
= $this->validateVariant( $language );
265 if ( $this->mHeaderVariant
) {
271 return $this->mHeaderVariant
;
275 * Caption convert, base on preg_replace_callback.
277 * To convert text in "title" or "alt", like '<img alt="text" ... '
278 * or '<span title="text" ... '
280 * @return String like ' alt="yyyy"' or ' title="yyyy"'
282 protected function captionConvert( $matches ) {
283 $toVariant = $this->getPreferredVariant();
284 $title = $matches[1];
286 // we convert captions except URL
287 if ( !strpos( $text, '://' ) ) {
288 $text = $this->translate( $text, $toVariant );
290 return " $title=\"$text\"";
294 * Dictionary-based conversion.
295 * This function would not parse the conversion rules.
296 * If you want to parse rules, try to use convert() or
299 * @param $text String: the text to be converted
300 * @param $toVariant String: the target language code
301 * @return String: the converted text
303 public function autoConvert( $text, $toVariant = false ) {
304 wfProfileIn( __METHOD__
);
309 $toVariant = $this->getPreferredVariant();
315 /* we convert everything except:
316 1. html markups (anything between < and >)
318 3. place holders created by the parser
321 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
322 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
327 // this one is needed when the text is inside an html markup
328 $htmlfix = '|<[^>]+$|^[^<>]*>';
330 // disable convert to variants between <code></code> tags
331 $codefix = '<code>.+?<\/code>|';
332 // disable convertsion of <script type="text/javascript"> ... </script>
333 $scriptfix = '<script.*?>.*?<\/script>|';
334 // disable conversion of <pre xxxx> ... </pre>
335 $prefix = '<pre.*?>.*?<\/pre>|';
337 $reg = '/' . $codefix . $scriptfix . $prefix .
338 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
340 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
342 $m = array_shift( $matches );
344 $ret = $this->translate( $m[0], $toVariant );
345 $mstart = $m[1] +
strlen( $m[0] );
347 // enable convertsion of '<img alt="xxxx" ... '
348 // or '<span title="xxxx" ... '
349 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
354 foreach ( $matches as $m ) {
355 $mark = substr( $text, $mstart, $m[1] - $mstart );
356 $mark = preg_replace_callback( $captionpattern,
357 array( &$this, 'captionConvert' ),
359 // Let's convert the trtext only once,
360 // it would give us more performance improvement
362 $trtext .= $m[0] . $trtextmark;
363 $mstart = $m[1] +
strlen( $m[0] );
366 $trtext = $this->translate( $trtext, $toVariant );
367 $trtext = StringUtils
::explode( $trtextmark, $trtext );
368 foreach ( $trtext as $t ) {
369 $ret .= array_shift( $notrtext );
372 wfProfileOut( __METHOD__
);
377 * Translate a string to a variant.
378 * Doesn't parse rules or do any of that other stuff, for that use
379 * convert() or convertTo().
381 * @param $text String: text to convert
382 * @param $variant String: variant language code
383 * @return String: translated text
385 protected function translate( $text, $variant ) {
386 wfProfileIn( __METHOD__
);
387 // If $text is empty or only includes spaces, do nothing
388 // Otherwise translate it
389 if ( trim( $text ) ) {
391 $text = $this->mTables
[$variant]->replace( $text );
393 wfProfileOut( __METHOD__
);
398 * Call translate() to convert text to all valid variants.
400 * @param $text String: the text to be converted
401 * @return Array: variant => converted text
403 public function autoConvertToAllVariants( $text ) {
404 wfProfileIn( __METHOD__
);
408 foreach ( $this->mVariants
as $variant ) {
409 $ret[$variant] = $this->translate( $text, $variant );
412 wfProfileOut( __METHOD__
);
417 * Convert link text to all valid variants.
418 * In the first, this function only convert text outside the
419 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
420 * titles, the text will get all converted always.
421 * So I removed this feature and deprecated the function.
423 * @param $text String: the text to be converted
424 * @return Array: variant => converted text
425 * @deprecated Use autoConvertToAllVariants() instead
427 public function convertLinkToAllVariants( $text ) {
428 return $this->autoConvertToAllVariants( $text );
432 * Apply manual conversion rules.
434 * @param $convRule Object: Object of ConverterRule
436 protected function applyManualConv( $convRule ) {
437 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
439 // Bug 24072: $mConvRuleTitle was overwritten by other manual
440 // rule(s) not for title, this breaks the title conversion.
441 $newConvRuleTitle = $convRule->getTitle();
442 if ( $newConvRuleTitle ) {
443 // So I add an empty check for getTitle()
444 $this->mConvRuleTitle
= $newConvRuleTitle;
447 // merge/remove manual conversion rules to/from global table
448 $convTable = $convRule->getConvTable();
449 $action = $convRule->getRulesAction();
450 foreach ( $convTable as $variant => $pair ) {
451 if ( !$this->validateVariant( $variant ) ) {
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 * Auto convert a Title object to a readable string in the
474 *@param $title Object: a object of Title
475 *@return String: converted title text
477 public function convertTitle( $title ) {
478 $variant = $this->getPreferredVariant();
479 $index = $title->getNamespace();
480 if ( $index === NS_MAIN
) {
483 // first let's check if a message has given us a converted name
484 $nsConvKey = 'conversion-ns' . $index;
485 if ( !wfEmptyMsg( $nsConvKey ) ) {
486 $text = wfMsgForContentNoTrans( $nsConvKey );
488 // the message does not exist, try retrieve it from the current
489 // variant's namespace names.
490 $langObj = $this->mLangObj
->factory( $variant );
491 $text = $langObj->getFormattedNsText( $index );
495 $text .= $title->getText();
496 $text = $this->translate( $text, $variant );
501 * Convert text to different variants of a language. The automatic
502 * conversion is done in autoConvert(). Here we parse the text
503 * marked with -{}-, which specifies special conversions of the
504 * text that can not be accomplished in autoConvert().
506 * Syntax of the markup:
507 * -{code1:text1;code2:text2;...}- or
508 * -{flags|code1:text1;code2:text2;...}- or
509 * -{text}- in which case no conversion should take place for text
511 * @param $text String: text to be converted
512 * @return String: converted text
514 public function convert( $text ) {
515 $variant = $this->getPreferredVariant();
516 return $this->convertTo( $text, $variant );
520 * Same as convert() except a extra parameter to custom variant.
522 * @param $text String: text to be converted
523 * @param $variant String: the target variant code
524 * @return String: converted text
526 public function convertTo( $text, $variant ) {
527 global $wgDisableLangConversion;
528 if ( $wgDisableLangConversion ) return $text;
529 return $this->recursiveConvertTopLevel( $text, $variant );
533 * Recursively convert text on the outside. Allow to use nested
534 * markups to custom rules.
536 * @param $text String: text to be converted
537 * @param $variant String: the target variant code
538 * @param $depth Integer: depth of recursion
539 * @return String: converted text
541 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
544 $length = strlen( $text );
545 while ( $startPos < $length ) {
546 $pos = strpos( $text, '-{', $startPos );
548 if ( $pos === false ) {
549 // No more markup, append final segment
550 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
556 // Append initial segment
557 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
562 // Do recursive conversion
563 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
570 * Recursively convert text on the inside.
572 * @param $text String: text to be converted
573 * @param $variant String: the target variant code
574 * @param $depth Integer: depth of recursion
575 * @return String: converted text
577 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
578 // Quick sanity check (no function calls)
579 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
580 throw new MWException( __METHOD__
. ': invalid input string' );
585 $warningDone = false;
586 $length = strlen( $text );
588 while ( $startPos < $length ) {
590 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
600 // Append initial segment
601 $inner .= substr( $text, $startPos, $pos - $startPos );
609 if ( $depth >= $this->mMaxDepth
) {
611 if ( !$warningDone ) {
612 $inner .= '<span class="error">' .
613 wfMsgForContent( 'language-converter-depth-warning',
621 // Recursively parse another rule
622 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
627 $rule = new ConverterRule( $inner, $this );
628 $rule->parse( $variant );
629 $this->applyManualConv( $rule );
630 return $rule->getDisplay();
632 throw new MWException( __METHOD__
. ': invalid regex match' );
637 if ( $startPos < $length ) {
638 $inner .= substr( $text, $startPos );
641 return '-{' . $this->autoConvert( $inner, $variant );
645 * If a language supports multiple variants, it is
646 * possible that non-existing link in one variant
647 * actually exists in another variant. This function
648 * tries to find it. See e.g. LanguageZh.php
650 * @param $link String: the name of the link
651 * @param $nt Mixed: the title object of the link
652 * @param $ignoreOtherCond Boolean: to disable other conditions when
653 * we need to transclude a template or update a category's link
654 * @return Null, the input parameters may be modified upon return
656 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
657 # If the article has already existed, there is no need to
658 # check it again, otherwise it may cause a fault.
659 if ( is_object( $nt ) && $nt->exists() ) {
663 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
665 $isredir = $wgRequest->getText( 'redirect', 'yes' );
666 $action = $wgRequest->getText( 'action' );
667 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
668 $disableLinkConversion = $wgDisableLangConversion
669 ||
$wgDisableTitleConversion;
670 $linkBatch = new LinkBatch();
674 if ( $disableLinkConversion ||
675 ( !$ignoreOtherCond &&
678 ||
$action == 'submit'
679 ||
$linkconvert == 'no'
680 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
684 if ( is_object( $nt ) ) {
685 $ns = $nt->getNamespace();
688 $variants = $this->autoConvertToAllVariants( $link );
689 if ( !$variants ) { // give up
695 foreach ( $variants as $v ) {
697 $varnt = Title
::newFromText( $v, $ns );
698 if ( !is_null( $varnt ) ) {
699 $linkBatch->addObj( $varnt );
705 // fetch all variants in single query
706 $linkBatch->execute();
708 foreach ( $titles as $varnt ) {
709 if ( $varnt->getArticleID() > 0 ) {
711 $link = $varnt->getText();
718 * Returns language specific hash options.
720 public function getExtraHashOptions() {
721 $variant = $this->getPreferredVariant();
722 return '!' . $variant ;
726 * Load default conversion tables.
727 * This method must be implemented in derived class.
731 function loadDefaultTables() {
732 $name = get_class( $this );
733 wfDie( "Must implement loadDefaultTables() method in class $name" );
737 * Load conversion tables either from the cache or the disk.
740 function loadTables( $fromcache = true ) {
741 if ( $this->mTablesLoaded
) {
745 wfProfileIn( __METHOD__
);
746 $this->mTablesLoaded
= true;
747 $this->mTables
= false;
749 wfProfileIn( __METHOD__
. '-cache' );
750 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
751 wfProfileOut( __METHOD__
. '-cache' );
754 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
755 wfProfileIn( __METHOD__
. '-recache' );
756 // not in cache, or we need a fresh reload.
757 // we will first load the default tables
758 // then update them using things in MediaWiki:Zhconversiontable/*
759 $this->loadDefaultTables();
760 foreach ( $this->mVariants
as $var ) {
761 $cached = $this->parseCachedTable( $var );
762 $this->mTables
[$var]->mergeArray( $cached );
765 $this->postLoadTables();
766 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
768 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
769 wfProfileOut( __METHOD__
. '-recache' );
771 wfProfileOut( __METHOD__
);
775 * Hook for post processig after conversion tables are loaded.
778 function postLoadTables() { }
781 * Reload the conversion tables.
785 function reloadTables() {
786 if ( $this->mTables
) {
787 unset( $this->mTables
);
789 $this->mTablesLoaded
= false;
790 $this->loadTables( false );
795 * Parse the conversion table stored in the cache.
797 * The tables should be in blocks of the following form:
804 * To make the tables more manageable, subpages are allowed
805 * and will be parsed recursively if $recursive == true.
808 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
809 global $wgMessageCache;
810 static $parsed = array();
812 if ( !is_object( $wgMessageCache ) ) {
816 $key = 'Conversiontable/' . $code;
818 $key .= '/' . $subpage;
820 if ( array_key_exists( $key, $parsed ) ) {
824 if ( strpos( $code, '/' ) === false ) {
825 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
826 if ( $txt === false ) {
827 # FIXME: this method doesn't seem to be expecting
828 # this possible outcome...
829 $txt = '<Conversiontable>';
832 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
833 "Conversiontable/$code" );
834 if ( $title && $title->exists() ) {
835 $article = new Article( $title );
836 $txt = $article->getContents();
842 // get all subpage links of the form
843 // [[MediaWiki:conversiontable/zh-xx/...|...]]
844 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
846 $subs = StringUtils
::explode( '[[', $txt );
848 foreach ( $subs as $sub ) {
849 $link = explode( ']]', $sub, 2 );
850 if ( count( $link ) != 2 ) {
853 $b = explode( '|', $link[0], 2 );
854 $b = explode( '/', trim( $b[0] ), 3 );
855 if ( count( $b ) == 3 ) {
861 if ( $b[0] == $linkhead && $b[1] == $code ) {
862 $sublinks[] = $sublink;
866 // parse the mappings in this page
867 $blocks = StringUtils
::explode( '-{', $txt );
870 foreach ( $blocks as $block ) {
872 // Skip the part before the first -{
876 $mappings = explode( '}-', $block, 2 );
877 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
879 $table = StringUtils
::explode( ';', $stripped );
880 foreach ( $table as $t ) {
881 $m = explode( '=>', $t, 3 );
882 if ( count( $m ) != 2 )
884 // trim any trailling comments starting with '//'
885 $tt = explode( '//', $m[1], 2 );
886 $ret[trim( $m[0] )] = trim( $tt[0] );
889 $parsed[$key] = true;
891 // recursively parse the subpages
893 foreach ( $sublinks as $link ) {
894 $s = $this->parseCachedTable( $code, $link, $recursive );
895 $ret = array_merge( $ret, $s );
899 if ( $this->mUcfirst
) {
900 foreach ( $ret as $k => $v ) {
901 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
908 * Enclose a string with the "no conversion" tag. This is used by
909 * various functions in the Parser.
911 * @param $text String: text to be tagged for no conversion
912 * @param $noParse Unused (?)
913 * @return String: the tagged text
915 public function markNoConversion( $text, $noParse = false ) {
916 # don't mark if already marked
917 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
921 $ret = "-{R|$text}-";
926 * Convert the sorting key for category links. This should make different
927 * keys that are variants of each other map to the same key.
929 function convertCategoryKey( $key ) {
934 * Hook to refresh the cache of conversion tables when
935 * MediaWiki:conversiontable* is updated.
938 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
939 $iswatch, $section, $flags, $revision ) {
940 $titleobj = $article->getTitle();
941 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
942 $title = $titleobj->getDBkey();
943 $t = explode( '/', $title, 3 );
945 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
946 if ( $this->validateVariant( $t[1] ) ) {
947 $this->reloadTables();
955 * Armour rendered math against conversion.
956 * Wrap math into rawoutput -{R| math }- syntax.
958 public function armourMath( $text ) {
959 // we need to convert '-{' and '}-' to '-{' and '}-'
960 // to avoid a unwanted '}-' appeared after the math-image.
961 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
962 $ret = "-{R|$text}-";
967 * Get the cached separator pattern for ConverterRule::parseRules()
969 function getVarSeparatorPattern() {
970 if ( is_null( $this->mVarSeparatorPattern
) ) {
971 // varsep_pattern for preg_split:
972 // text should be splited by ";" only if a valid variant
973 // name exist after the markup, for example:
974 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
975 // <span style="font-size:120%;">yyy</span>;}-
976 // we should split it as:
978 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
979 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
983 foreach ( $this->mVariants
as $variant ) {
984 // zh-hans:xxx;zh-hant:yyy
985 $pat .= $variant . '\s*:|';
986 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
987 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
990 $this->mVarSeparatorPattern
= $pat;
992 return $this->mVarSeparatorPattern
;
997 * Parser for rules of language conversion , parse rules in -{ }- tag.
999 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1001 class ConverterRule
{
1002 var $mText; // original text in -{text}-
1003 var $mConverter; // LanguageConverter object
1004 var $mManualCodeError = '<strong class="error">code error!</strong>';
1005 var $mRuleDisplay = '';
1006 var $mRuleTitle = false;
1007 var $mRules = '';// string : the text of the rules
1008 var $mRulesAction = 'none';
1009 var $mFlags = array();
1010 var $mVariantFlags = array();
1011 var $mConvTable = array();
1012 var $mBidtable = array();// array of the translation in each variant
1013 var $mUnidtable = array();// array of the translation in each variant
1018 * @param $text String: the text between -{ and }-
1019 * @param $converter LanguageConverter object
1021 public function __construct( $text, $converter ) {
1022 $this->mText
= $text;
1023 $this->mConverter
= $converter;
1027 * Check if variants array in convert array.
1029 * @param $variants Array or string: variant language code
1030 * @return String: translated text
1032 public function getTextInBidtable( $variants ) {
1033 $variants = (array)$variants;
1037 foreach ( $variants as $variant ) {
1038 if ( isset( $this->mBidtable
[$variant] ) ) {
1039 return $this->mBidtable
[$variant];
1046 * Parse flags with syntax -{FLAG| ... }-
1049 function parseFlags() {
1050 $text = $this->mText
;
1052 $variantFlags = array();
1054 $sepPos = strpos( $text, '|' );
1055 if ( $sepPos !== false ) {
1056 $validFlags = $this->mConverter
->mFlags
;
1057 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1058 foreach ( $f as $ff ) {
1060 if ( isset( $validFlags[$ff] ) ) {
1061 $flags[$validFlags[$ff]] = true;
1064 $text = strval( substr( $text, $sepPos +
1 ) );
1069 } elseif ( isset( $flags['R'] ) ) {
1070 $flags = array( 'R' => true );// remove other flags
1071 } elseif ( isset( $flags['N'] ) ) {
1072 $flags = array( 'N' => true );// remove other flags
1073 } elseif ( isset( $flags['-'] ) ) {
1074 $flags = array( '-' => true );// remove other flags
1075 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1077 } elseif ( isset( $flags['H'] ) ) {
1078 // replace A flag, and remove other flags except T
1079 $temp = array( '+' => true, 'H' => true );
1080 if ( isset( $flags['T'] ) ) {
1083 if ( isset( $flags['D'] ) ) {
1088 if ( isset( $flags['A'] ) ) {
1092 if ( isset( $flags['D'] ) ) {
1093 unset( $flags['S'] );
1095 // try to find flags like "zh-hans", "zh-hant"
1096 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1097 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1098 if ( $variantFlags ) {
1099 $variantFlags = array_flip( $variantFlags );
1103 $this->mVariantFlags
= $variantFlags;
1104 $this->mRules
= $text;
1105 $this->mFlags
= $flags;
1109 * Generate conversion table.
1112 function parseRules() {
1113 $rules = $this->mRules
;
1114 $bidtable = array();
1115 $unidtable = array();
1116 $variants = $this->mConverter
->mVariants
;
1117 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1119 $choice = preg_split( $varsep_pattern, $rules );
1121 foreach ( $choice as $c ) {
1122 $v = explode( ':', $c, 2 );
1123 if ( count( $v ) != 2 ) {
1124 // syntax error, skip
1127 $to = trim( $v[1] );
1129 $u = explode( '=>', $v, 2 );
1130 // if $to is empty, strtr() could return a wrong result
1131 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1132 $bidtable[$v] = $to;
1133 } elseif ( count( $u ) == 2 ) {
1134 $from = trim( $u[0] );
1136 if ( array_key_exists( $v, $unidtable )
1137 && !is_array( $unidtable[$v] )
1139 && in_array( $v, $variants ) ) {
1140 $unidtable[$v] = array( $from => $to );
1141 } elseif ( $to && in_array( $v, $variants ) ) {
1142 $unidtable[$v][$from] = $to;
1145 // syntax error, pass
1146 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1147 $bidtable = array();
1148 $unidtable = array();
1152 $this->mBidtable
= $bidtable;
1153 $this->mUnidtable
= $unidtable;
1159 function getRulesDesc() {
1160 $codesep = $this->mConverter
->mDescCodeSep
;
1161 $varsep = $this->mConverter
->mDescVarSep
;
1163 foreach ( $this->mBidtable
as $k => $v ) {
1164 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1166 foreach ( $this->mUnidtable
as $k => $a ) {
1167 foreach ( $a as $from => $to ) {
1168 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1169 "$codesep$to$varsep";
1176 * Parse rules conversion.
1179 function getRuleConvertedStr( $variant ) {
1180 $bidtable = $this->mBidtable
;
1181 $unidtable = $this->mUnidtable
;
1183 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1184 return $this->mRules
;
1186 // display current variant in bidirectional array
1187 $disp = $this->getTextInBidtable( $variant );
1188 // or display current variant in fallbacks
1190 $disp = $this->getTextInBidtable(
1191 $this->mConverter
->getVariantFallbacks( $variant ) );
1193 // or display current variant in unidirectional array
1194 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1195 $disp = array_values( $unidtable[$variant] );
1198 // or display frist text under disable manual convert
1200 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1201 if ( count( $bidtable ) > 0 ) {
1202 $disp = array_values( $bidtable );
1205 $disp = array_values( $unidtable );
1206 $disp = array_values( $disp[0] );
1215 * Generate conversion table for all text.
1218 function generateConvTable() {
1219 // Special case optimisation
1220 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1221 $this->mConvTable
= array();
1225 $bidtable = $this->mBidtable
;
1226 $unidtable = $this->mUnidtable
;
1227 $manLevel = $this->mConverter
->mManualLevel
;
1230 foreach ( $this->mConverter
->mVariants
as $v ) {
1231 /* for bidirectional array
1232 fill in the missing variants, if any,
1234 if ( !isset( $bidtable[$v] ) ) {
1236 $this->mConverter
->getVariantFallbacks( $v );
1237 $vf = $this->getTextInBidtable( $variantFallbacks );
1239 $bidtable[$v] = $vf;
1243 if ( isset( $bidtable[$v] ) ) {
1244 foreach ( $vmarked as $vo ) {
1245 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1246 // or -{H|zh:WordZh;zh-tw:WordTw}-
1247 // or -{-|zh:WordZh;zh-tw:WordTw}-
1248 // to introduce a custom mapping between
1249 // words WordZh and WordTw in the whole text
1250 if ( $manLevel[$v] == 'bidirectional' ) {
1251 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1253 if ( $manLevel[$vo] == 'bidirectional' ) {
1254 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1259 /*for unidirectional array fill to convert tables */
1260 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1261 && isset( $unidtable[$v] ) )
1263 if ( isset( $this->mConvTable
[$v] ) ) {
1264 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1266 $this->mConvTable
[$v] = $unidtable[$v];
1273 * Parse rules and flags.
1276 function parse( $variant = NULL ) {
1278 $variant = $this->mConverter
->getPreferredVariant();
1281 $this->parseFlags();
1282 $flags = $this->mFlags
;
1284 // convert to specified variant
1285 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1286 if ( $this->mVariantFlags
) {
1287 // check if current variant in flags
1288 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1289 // then convert <text to convert> to current language
1290 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1292 } else { // if current variant no in flags,
1293 // then we check its fallback variants.
1295 $this->mConverter
->getVariantFallbacks( $variant );
1296 foreach ( $variantFallbacks as $variantFallback ) {
1297 // if current variant's fallback exist in flags
1298 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1299 // then convert <text to convert> to fallback language
1301 $this->mConverter
->autoConvert( $this->mRules
,
1307 $this->mFlags
= $flags = array( 'R' => true );
1310 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1311 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1312 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1313 $this->parseRules();
1315 $rules = $this->mRules
;
1317 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1318 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1319 // fill all variants if text in -{A/H/-|text} without rules
1320 foreach ( $this->mConverter
->mVariants
as $v ) {
1321 $this->mBidtable
[$v] = $rules;
1323 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1324 $this->mFlags
= $flags = array( 'R' => true );
1328 $this->mRuleDisplay
= false;
1329 foreach ( $flags as $flag => $unused ) {
1332 // if we don't do content convert, still strip the -{}- tags
1333 $this->mRuleDisplay
= $rules;
1336 // process N flag: output current variant name
1337 $ruleVar = trim( $rules );
1338 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1339 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1341 $this->mRuleDisplay
= '';
1345 // process D flag: output rules description
1346 $this->mRuleDisplay
= $this->getRulesDesc();
1349 // process H,- flag or T only: output nothing
1350 $this->mRuleDisplay
= '';
1353 $this->mRulesAction
= 'remove';
1354 $this->mRuleDisplay
= '';
1357 $this->mRulesAction
= 'add';
1358 $this->mRuleDisplay
= '';
1361 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1364 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1365 $this->mRuleDisplay
= '';
1368 // ignore unknown flags (but see error case below)
1371 if ( $this->mRuleDisplay
=== false ) {
1372 $this->mRuleDisplay
= $this->mManualCodeError
;
1375 $this->generateConvTable();
1381 function hasRules() {
1386 * Get display text on markup -{...}-
1389 function getDisplay() {
1390 return $this->mRuleDisplay
;
1394 * Get converted title.
1397 function getTitle() {
1398 return $this->mRuleTitle
;
1402 * Return how deal with conversion rules.
1405 function getRulesAction() {
1406 return $this->mRulesAction
;
1410 * Get conversion table. ( bidirectional and unidirectional
1411 * conversion table )
1414 function getConvTable() {
1415 return $this->mConvTable
;
1419 * Get conversion rules string.
1422 function getRules() {
1423 return $this->mRules
;
1427 * Get conversion flags.
1430 function getFlags() {
1431 return $this->mFlags
;