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 var $mNamespaceTables;
24 // 'bidirectional' 'unidirectional' 'disable' for each variant
29 var $mDescCodeSep = ':', $mDescVarSep = ';';
30 var $mUcfirst = false;
31 var $mConvRuleTitle = false;
36 var $mVarSeparatorPattern;
38 const CACHE_VERSION_KEY
= 'VERSION 6';
43 * @param $langobj The Language Object
44 * @param $maincode String: the main language code of this language
45 * @param $variants Array: the supported variants of this language
46 * @param $variantfallbacks Array: the fallback language of each variant
47 * @param $flags Array: defining the custom strings that maps to the flags
48 * @param $manualLevel Array: limit for supported variants
50 public function __construct( $langobj, $maincode,
52 $variantfallbacks = array(),
54 $manualLevel = array() ) {
55 $this->mLangObj
= $langobj;
56 $this->mMainLanguageCode
= $maincode;
58 global $wgDisabledVariants;
59 $this->mVariants
= array();
60 foreach ( $variants as $variant ) {
61 if ( !in_array( $variant, $wgDisabledVariants ) ) {
62 $this->mVariants
[] = $variant;
65 $this->mVariantFallbacks
= $variantfallbacks;
66 global $wgLanguageNames;
67 $this->mVariantNames
= $wgLanguageNames;
68 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
70 // 'S' show converted text
71 // '+' add rules for alltext
72 // 'E' the gave flags is error
73 // these flags above are reserved for program
74 'A' => 'A', // add rule for convert code (all text convert)
75 'T' => 'T', // title convert
76 'R' => 'R', // raw content
77 'D' => 'D', // convert description (subclass implement)
78 '-' => '-', // remove convert (not implement)
79 'H' => 'H', // add rule for convert code
80 // (but no display in placed code )
81 'N' => 'N' // current variant name
83 $this->mFlags
= array_merge( $f, $flags );
84 foreach ( $this->mVariants
as $v ) {
85 if ( array_key_exists( $v, $manualLevel ) ) {
86 $this->mManualLevel
[$v] = $manualLevel[$v];
88 $this->mManualLevel
[$v] = 'bidirectional';
90 $this->mNamespaceTables
[$v] = array();
91 $this->mFlags
[$v] = $v;
98 function getVariants() {
99 return $this->mVariants
;
103 * In case some variant is not defined in the markup, we need
104 * to have some fallback. For example, in zh, normally people
105 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
106 * when zh-sg is preferred but not defined, we will pick zh-hans
107 * in this case. Right now this is only used by zh.
109 * @param $v String: the language code of the variant
110 * @return string array The code of the fallback language or false if there
113 public function getVariantFallbacks( $v ) {
114 if ( isset( $this->mVariantFallbacks
[$v] ) ) {
115 return $this->mVariantFallbacks
[$v];
117 return $this->mMainLanguageCode
;
121 * Get the title produced by the conversion rule.
124 function getConvRuleTitle() {
125 return $this->mConvRuleTitle
;
129 * Get preferred language variants.
130 * @param $fromUser Boolean: get it from $wgUser's preferences
131 * @param $fromHeader Boolean: get it from Accept-Language
132 * @return String: the preferred language code
134 public function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
135 global $wgDefaultLanguageVariant;
137 $req = $this->getURLVariant();
139 if ( $fromUser && !$req ) {
140 $req = $this->getUserVariant();
143 if ( $fromHeader && !$req ) {
144 $req = $this->getHeaderVariant();
147 if ( $wgDefaultLanguageVariant && !$req ) {
148 $req = $this->validateVariant( $wgDefaultLanguageVariant );
151 // This function, unlike the other get*Variant functions, is
152 // not memoized (i.e. there return value is not cached) since
153 // new information might appear during processing after this
158 return $this->mMainLanguageCode
;
162 * Validate the variant
163 * @param $v String: the variant to validate
164 * @return Mixed: returns the variant if it is valid, null otherwise
166 function validateVariant( $v = null ) {
167 if ( $v !== null && in_array( $v, $this->mVariants
) ) {
174 * Get the variant specified in the URL
176 * @return Mixed: variant if one found, false otherwise.
178 function getURLVariant() {
182 if ( $this->mURLVariant
) {
183 return $this->mURLVariant
;
186 // see if the preference is set in the request
187 $ret = $wgRequest->getText( 'variant' );
190 $ret = $wgRequest->getVal( 'uselang' );
193 return $this->mURLVariant
= $this->validateVariant( $ret );
197 * Determine if the user has a variant set.
199 * @return Mixed: variant if one found, false otherwise.
201 function getUserVariant() {
205 // memoizing this function wreaks havoc on parserTest.php
206 /* if ( $this->mUserVariant ) { */
207 /* return $this->mUserVariant; */
210 // get language variant preference from logged in users
211 // Don't call this on stub objects because that causes infinite
212 // recursion during initialisation
213 if ( $wgUser->isLoggedIn() ) {
214 $ret = $wgUser->getOption( 'variant' );
217 // figure out user lang without constructing wgLang to avoid
218 // infinite recursion
219 $ret = $wgUser->getOption( 'language' );
222 return $this->mUserVariant
= $this->validateVariant( $ret );
227 * Determine the language variant from the Accept-Language header.
229 * @return Mixed: variant if one found, false otherwise.
231 function getHeaderVariant() {
235 if ( $this->mHeaderVariant
) {
236 return $this->mHeaderVariant
;
239 // see if some supported language variant is set in the
242 $acceptLanguage = $wgRequest->getHeader( 'Accept-Language' );
243 if ( !$acceptLanguage ) {
248 $result = StringUtils
::explode( ',', strtolower( $acceptLanguage ) );
249 $languages = array();
251 foreach ( $result as $elem ) {
252 // if $elem likes 'zh-cn;q=0.9'
253 if ( ( $posi = strpos( $elem, ';' ) ) !== false ) {
254 // get the real language code likes 'zh-cn'
255 $languages[] = substr( $elem, 0, $posi );
257 $languages[] = $elem;
261 $fallback_languages = array();
262 foreach ( $languages as $language ) {
264 $language = trim( $language );
265 $this->mHeaderVariant
= $this->validateVariant( $language );
266 if ( $this->mHeaderVariant
) {
270 // To see if there are fallbacks of current language.
271 // We record these fallback variants, and process
273 $fallbacks = $this->getVariantFallbacks( $language );
274 if ( is_string( $fallbacks ) ) {
275 $fallback_languages[] = $fallbacks;
276 } elseif ( is_array( $fallbacks ) ) {
277 $fallback_languages =
278 array_merge( $fallback_languages,
283 if ( !$this->mHeaderVariant
) {
284 // process fallback languages now
285 $fallback_languages = array_unique( $fallback_languages );
286 foreach ( $fallback_languages as $language ) {
287 $this->mHeaderVariant
= $this->validateVariant( $language );
288 if ( $this->mHeaderVariant
) {
294 return $this->mHeaderVariant
;
298 * Caption convert, base on preg_replace_callback.
300 * To convert text in "title" or "alt", like '<img alt="text" ... '
301 * or '<span title="text" ... '
303 * @return String like ' alt="yyyy"' or ' title="yyyy"'
306 function captionConvert( $matches ) {
307 $toVariant = $this->getPreferredVariant();
308 $title = $matches[1];
310 // we convert captions except URL
311 if ( !strpos( $text, '://' ) ) {
312 $text = $this->translate( $text, $toVariant );
314 return " $title=\"$text\"";
318 * Dictionary-based conversion.
320 * @param $text String: the text to be converted
321 * @param $toVariant String: the target language code
322 * @return String: the converted text
325 function autoConvert( $text, $toVariant = false ) {
326 $fname = 'LanguageConverter::autoConvert';
328 wfProfileIn( $fname );
330 if ( !$this->mTablesLoaded
) {
335 $toVariant = $this->getPreferredVariant();
341 /* we convert everything except:
342 1. html markups (anything between < and >)
344 3. place holders created by the parser
347 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
348 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
353 // this one is needed when the text is inside an html markup
354 $htmlfix = '|<[^>]+$|^[^<>]*>';
356 // disable convert to variants between <code></code> tags
357 $codefix = '<code>.+?<\/code>|';
358 // disable convertsion of <script type="text/javascript"> ... </script>
359 $scriptfix = '<script.*?>.*?<\/script>|';
360 // disable conversion of <pre xxxx> ... </pre>
361 $prefix = '<pre.*?>.*?<\/pre>|';
363 $reg = '/' . $codefix . $scriptfix . $prefix .
364 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
366 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
368 $m = array_shift( $matches );
370 $ret = $this->translate( $m[0], $toVariant );
371 $mstart = $m[1] +
strlen( $m[0] );
373 // enable convertsion of '<img alt="xxxx" ... '
374 // or '<span title="xxxx" ... '
375 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
380 foreach ( $matches as $m ) {
381 $mark = substr( $text, $mstart, $m[1] - $mstart );
382 $mark = preg_replace_callback( $captionpattern,
383 array( &$this, 'captionConvert' ),
385 // Let's convert the trtext only once,
386 // it would give us more performance improvement
388 $trtext .= $m[0] . $trtextmark;
389 $mstart = $m[1] +
strlen( $m[0] );
392 $trtext = $this->translate( $trtext, $toVariant );
393 $trtext = StringUtils
::explode( $trtextmark, $trtext );
394 foreach ( $trtext as $t ) {
395 $ret .= array_shift( $notrtext );
398 wfProfileOut( $fname );
403 * Translate a string to a variant.
404 * Doesn't process markup or do any of that other stuff, for that use
407 * @param $text String: text to convert
408 * @param $variant String: variant language code
409 * @return String: translated text
412 function translate( $text, $variant ) {
413 wfProfileIn( __METHOD__
);
414 // If $text is empty or only includes spaces, do nothing
415 // Otherwise translate it
416 if ( trim( $text ) ) {
417 if ( !$this->mTablesLoaded
) {
420 $text = $this->mTables
[$variant]->replace( $text );
422 wfProfileOut( __METHOD__
);
427 * Convert text to all supported variants.
429 * @param $text String: the text to be converted
430 * @return Array of string
432 public function autoConvertToAllVariants( $text ) {
433 $fname = 'LanguageConverter::autoConvertToAllVariants';
434 wfProfileIn( $fname );
435 if ( !$this->mTablesLoaded
) {
440 foreach ( $this->mVariants
as $variant ) {
441 $ret[$variant] = $this->translate( $text, $variant );
444 wfProfileOut( $fname );
449 * Convert link text to all supported variants.
451 * @param $text String: the text to be converted
452 * @return Array of string
454 public function convertLinkToAllVariants( $text ) {
455 if ( !$this->mTablesLoaded
) {
460 $tarray = StringUtils
::explode( '-{', $text );
463 foreach ( $tarray as $txt ) {
466 foreach ( $this->mVariants
as $variant ) {
467 $ret[$variant] = $this->translate( $txt, $variant );
472 $marked = explode( '}-', $txt, 2 );
474 foreach ( $this->mVariants
as $variant ) {
475 $ret[$variant] .= '-{' . $marked[0] . '}-';
476 if ( array_key_exists( 1, $marked ) ) {
477 $ret[$variant] .= $this->translate( $marked[1], $variant );
487 * Prepare manual conversion table.
490 function applyManualConv( $convRule ) {
491 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom
492 // conversion in title
493 $this->mConvRuleTitle
= $convRule->getTitle();
495 // apply manual conversion table to global table
496 $convTable = $convRule->getConvTable();
497 $action = $convRule->getRulesAction();
498 foreach ( $convTable as $variant => $pair ) {
499 if ( !$this->validateVariant( $variant ) ) {
503 if ( $action == 'add' ) {
504 foreach ( $pair as $from => $to ) {
505 // to ensure that $from and $to not be left blank
506 // so $this->translate() could always return a string
507 if ( $from ||
$to ) {
508 // more efficient than array_merge(), about 2.5 times.
509 $this->mTables
[$variant]->setPair( $from, $to );
512 } elseif ( $action == 'remove' ) {
513 $this->mTables
[$variant]->removeArray( $pair );
519 * Convert text to different variants of a language. The automatic
520 * conversion is done in autoConvert(). Here we parse the text
521 * marked with -{}-, which specifies special conversions of the
522 * text that can not be accomplished in autoConvert().
524 * Syntax of the markup:
525 * -{code1:text1;code2:text2;...}- or
526 * -{flags|code1:text1;code2:text2;...}- or
527 * -{text}- in which case no conversion should take place for text
529 * @param $text String: text to be converted
530 * @return String: converted text
532 public function convert( $text ) {
533 global $wgDisableLangConversion;
534 if ( $wgDisableLangConversion ) return $text;
536 $variant = $this->getPreferredVariant();
538 return $this->recursiveConvertTopLevel( $text, $variant );
542 * Convert a Title object to a readable string in the preferred variant
544 public function convertTitle( $title ) {
545 $variant = $this->getPreferredVariant();
546 if ( $title->getNamespace() === NS_MAIN
) {
549 $text = $title->getNsText();
550 if ( isset( $this->mNamespaceTables
[$variant][$text] ) ) {
551 $text = $this->mNamespaceTables
[$variant][$text];
555 $text .= $title->getText();
556 $text = $this->autoConvert( $text, $variant );
560 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
563 $length = strlen( $text );
564 while ( $startPos < $length ) {
566 $pos = strpos( $text, '-{', $startPos );
568 if ( $pos === false ) {
569 // No more markup, append final segment
570 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
576 // Append initial segment
577 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
582 // Do recursive conversion
583 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
589 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
590 // Quick sanity check (no function calls)
591 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
592 throw new MWException( __METHOD__
.': invalid input string' );
597 $warningDone = false;
598 $length = strlen( $text );
600 while ( $startPos < $length ) {
602 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
612 // Append initial segment
613 $inner .= substr( $text, $startPos, $pos - $startPos );
621 if ( $depth >= $this->mMaxDepth
) {
623 if ( !$warningDone ) {
624 $inner .= '<span class="error">' .
625 wfMsgForContent( 'language-converter-depth-warning',
633 // Recursively parse another rule
634 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
639 $rule = new ConverterRule( $inner, $this );
640 $rule->parse( $variant );
641 $this->applyManualConv( $rule );
642 return $rule->getDisplay();
644 throw new MWException( __METHOD__
.': invalid regex match' );
649 if ( $startPos < $length ) {
650 $inner .= substr( $text, $startPos );
653 return '-{' . $this->autoConvert( $inner, $variant );
657 * If a language supports multiple variants, it is
658 * possible that non-existing link in one variant
659 * actually exists in another variant. This function
660 * tries to find it. See e.g. LanguageZh.php
662 * @param $link String: the name of the link
663 * @param $nt Mixed: the title object of the link
664 * @param $ignoreOtherCond Boolean: to disable other conditions when
665 * we need to transclude a template or update a category's link
666 * @return Null, the input parameters may be modified upon return
668 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
669 # If the article has already existed, there is no need to
670 # check it again, otherwise it may cause a fault.
671 if ( is_object( $nt ) && $nt->exists() ) {
675 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
677 $isredir = $wgRequest->getText( 'redirect', 'yes' );
678 $action = $wgRequest->getText( 'action' );
679 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
680 $disableLinkConversion = $wgDisableLangConversion
681 ||
$wgDisableTitleConversion;
682 $linkBatch = new LinkBatch();
686 if ( $disableLinkConversion ||
687 ( !$ignoreOtherCond &&
690 ||
$action == 'submit'
691 ||
$linkconvert == 'no'
692 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
696 if ( is_object( $nt ) ) {
697 $ns = $nt->getNamespace();
700 $variants = $this->autoConvertToAllVariants( $link );
701 if ( !$variants ) { // give up
707 foreach ( $variants as $v ) {
709 $varnt = Title
::newFromText( $v, $ns );
710 if ( !is_null( $varnt ) ) {
711 $linkBatch->addObj( $varnt );
717 // fetch all variants in single query
718 $linkBatch->execute();
720 foreach ( $titles as $varnt ) {
721 if ( $varnt->getArticleID() > 0 ) {
723 $link = $varnt->getText();
730 * Returns language specific hash options.
732 public function getExtraHashOptions() {
733 $variant = $this->getPreferredVariant();
734 return '!' . $variant ;
738 * Load default conversion tables.
739 * This method must be implemented in derived class.
743 function loadDefaultTables() {
744 $name = get_class( $this );
745 wfDie( "Must implement loadDefaultTables() method in class $name" );
749 * Load conversion tables either from the cache or the disk.
752 function loadTables( $fromcache = true ) {
754 if ( $this->mTablesLoaded
) {
757 wfProfileIn( __METHOD__
);
758 $this->mTablesLoaded
= true;
759 $this->mTables
= false;
761 wfProfileIn( __METHOD__
. '-cache' );
762 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
763 wfProfileOut( __METHOD__
. '-cache' );
766 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
767 wfProfileIn( __METHOD__
. '-recache' );
768 // not in cache, or we need a fresh reload.
769 // we will first load the default tables
770 // then update them using things in MediaWiki:Zhconversiontable/*
771 $this->loadDefaultTables();
772 foreach ( $this->mVariants
as $var ) {
773 $cached = $this->parseCachedTable( $var );
774 $this->mTables
[$var]->mergeArray( $cached );
777 $this->postLoadTables();
778 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
780 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
781 wfProfileOut( __METHOD__
. '-recache' );
783 wfProfileOut( __METHOD__
);
787 * Hook for post processig after conversion tables are loaded.
790 function postLoadTables() { }
793 * Reload the conversion tables.
797 function reloadTables() {
798 if ( $this->mTables
) {
799 unset( $this->mTables
);
801 $this->mTablesLoaded
= false;
802 $this->loadTables( false );
807 * Parse the conversion table stored in the cache.
809 * The tables should be in blocks of the following form:
816 * To make the tables more manageable, subpages are allowed
817 * and will be parsed recursively if $recursive == true.
820 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
821 global $wgMessageCache;
822 static $parsed = array();
824 if ( !is_object( $wgMessageCache ) ) {
828 $key = 'Conversiontable/' . $code;
830 $key .= '/' . $subpage;
832 if ( array_key_exists( $key, $parsed ) ) {
836 if ( strpos( $code, '/' ) === false ) {
837 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
838 if( $txt === false ){
839 # FIXME: this method doesn't seem to be expecting
840 # this possible outcome...
841 $txt = '<Conversiontable>';
844 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
845 "Conversiontable/$code" );
846 if ( $title && $title->exists() ) {
847 $article = new Article( $title );
848 $txt = $article->getContents();
854 // get all subpage links of the form
855 // [[MediaWiki:conversiontable/zh-xx/...|...]]
856 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
858 $subs = StringUtils
::explode( '[[', $txt );
860 foreach ( $subs as $sub ) {
861 $link = explode( ']]', $sub, 2 );
862 if ( count( $link ) != 2 ) {
865 $b = explode( '|', $link[0], 2 );
866 $b = explode( '/', trim( $b[0] ), 3 );
867 if ( count( $b ) == 3 ) {
873 if ( $b[0] == $linkhead && $b[1] == $code ) {
874 $sublinks[] = $sublink;
879 // parse the mappings in this page
880 $blocks = StringUtils
::explode( '-{', $txt );
883 foreach ( $blocks as $block ) {
885 // Skip the part before the first -{
889 $mappings = explode( '}-', $block, 2 );
890 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
892 $table = StringUtils
::explode( ';', $stripped );
893 foreach ( $table as $t ) {
894 $m = explode( '=>', $t, 3 );
895 if ( count( $m ) != 2 )
897 // trim any trailling comments starting with '//'
898 $tt = explode( '//', $m[1], 2 );
899 $ret[trim( $m[0] )] = trim( $tt[0] );
902 $parsed[$key] = true;
905 // recursively parse the subpages
907 foreach ( $sublinks as $link ) {
908 $s = $this->parseCachedTable( $code, $link, $recursive );
909 $ret = array_merge( $ret, $s );
913 if ( $this->mUcfirst
) {
914 foreach ( $ret as $k => $v ) {
915 $ret[Language
::ucfirst( $k )] = Language
::ucfirst( $v );
922 * Enclose a string with the "no conversion" tag. This is used by
923 * various functions in the Parser.
925 * @param $text String: text to be tagged for no conversion
926 * @param $noParse Unused (?)
927 * @return String: the tagged text
929 public function markNoConversion( $text, $noParse = false ) {
930 # don't mark if already marked
931 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
935 $ret = "-{R|$text}-";
940 * Convert the sorting key for category links. This should make different
941 * keys that are variants of each other map to the same key.
943 function convertCategoryKey( $key ) {
948 * Hook to refresh the cache of conversion tables when
949 * MediaWiki:conversiontable* is updated.
952 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
953 $iswatch, $section, $flags, $revision ) {
954 $titleobj = $article->getTitle();
955 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
956 $title = $titleobj->getDBkey();
957 $t = explode( '/', $title, 3 );
959 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
960 if ( $this->validateVariant( $t[1] ) ) {
961 $this->reloadTables();
969 * Armour rendered math against conversion.
970 * Wrap math into rawoutput -{R| math }- syntax.
972 public function armourMath( $text ) {
973 // we need to convert '-{' and '}-' to '-{' and '}-'
974 // to avoid a unwanted '}-' appeared after the math-image.
975 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
976 $ret = "-{R|$text}-";
981 * Get the cached separator pattern for ConverterRule::parseRules()
983 function getVarSeparatorPattern() {
984 if ( is_null( $this->mVarSeparatorPattern
) ) {
985 // varsep_pattern for preg_split:
986 // text should be splited by ";" only if a valid variant
987 // name exist after the markup, for example:
988 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
989 // <span style="font-size:120%;">yyy</span>;}-
990 // we should split it as:
992 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
993 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
997 foreach ( $this->mVariants
as $variant ) {
998 // zh-hans:xxx;zh-hant:yyy
999 $pat .= $variant . '\s*:|';
1000 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1001 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1004 $this->mVarSeparatorPattern
= $pat;
1006 return $this->mVarSeparatorPattern
;
1011 * Parser for rules of language conversion , parse rules in -{ }- tag.
1013 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1015 class ConverterRule
{
1016 var $mText; // original text in -{text}-
1017 var $mConverter; // LanguageConverter object
1018 var $mManualCodeError = '<strong class="error">code error!</strong>';
1019 var $mRuleDisplay = '';
1020 var $mRuleTitle = false;
1021 var $mRules = '';// string : the text of the rules
1022 var $mRulesAction = 'none';
1023 var $mFlags = array();
1024 var $mVariantFlags = array();
1025 var $mConvTable = array();
1026 var $mBidtable = array();// array of the translation in each variant
1027 var $mUnidtable = array();// array of the translation in each variant
1032 * @param $text String: the text between -{ and }-
1033 * @param $converter LanguageConverter object
1035 public function __construct( $text, $converter ) {
1036 $this->mText
= $text;
1037 $this->mConverter
= $converter;
1041 * Check if variants array in convert array.
1043 * @param $variants Array or string: variant language code
1044 * @return String: translated text
1046 public function getTextInBidtable( $variants ) {
1047 $variants = (array)$variants;
1051 foreach ( $variants as $variant ) {
1052 if ( isset( $this->mBidtable
[$variant] ) ) {
1053 return $this->mBidtable
[$variant];
1060 * Parse flags with syntax -{FLAG| ... }-
1063 function parseFlags() {
1064 $text = $this->mText
;
1066 $variantFlags = array();
1068 $sepPos = strpos( $text, '|' );
1069 if ( $sepPos !== false ) {
1070 $validFlags = $this->mConverter
->mFlags
;
1071 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1072 foreach ( $f as $ff ) {
1074 if ( isset( $validFlags[$ff] ) ) {
1075 $flags[$validFlags[$ff]] = true;
1078 $text = strval( substr( $text, $sepPos +
1 ) );
1083 } elseif ( isset( $flags['R'] ) ) {
1084 $flags = array( 'R' => true );// remove other flags
1085 } elseif ( isset( $flags['N'] ) ) {
1086 $flags = array( 'N' => true );// remove other flags
1087 } elseif ( isset( $flags['-'] ) ) {
1088 $flags = array( '-' => true );// remove other flags
1089 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1091 } elseif ( isset( $flags['H'] ) ) {
1092 // replace A flag, and remove other flags except T
1093 $temp = array( '+' => true, 'H' => true );
1094 if ( isset( $flags['T'] ) ) {
1097 if ( isset( $flags['D'] ) ) {
1102 if ( isset( $flags['A'] ) ) {
1106 if ( isset( $flags['D'] ) ) {
1107 unset( $flags['S'] );
1109 // try to find flags like "zh-hans", "zh-hant"
1110 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1111 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1112 if ( $variantFlags ) {
1113 $variantFlags = array_flip( $variantFlags );
1117 $this->mVariantFlags
= $variantFlags;
1118 $this->mRules
= $text;
1119 $this->mFlags
= $flags;
1123 * Generate conversion table.
1126 function parseRules() {
1127 $rules = $this->mRules
;
1128 $flags = $this->mFlags
;
1129 $bidtable = array();
1130 $unidtable = array();
1131 $variants = $this->mConverter
->mVariants
;
1132 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1134 $choice = preg_split( $varsep_pattern, $rules );
1136 foreach ( $choice as $c ) {
1137 $v = explode( ':', $c, 2 );
1138 if ( count( $v ) != 2 ) {
1139 // syntax error, skip
1142 $to = trim( $v[1] );
1144 $u = explode( '=>', $v, 2 );
1145 // if $to is empty, strtr() could return a wrong result
1146 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1147 $bidtable[$v] = $to;
1148 } elseif ( count( $u ) == 2 ) {
1149 $from = trim( $u[0] );
1151 if ( array_key_exists( $v, $unidtable )
1152 && !is_array( $unidtable[$v] )
1154 && in_array( $v, $variants ) ) {
1155 $unidtable[$v] = array( $from => $to );
1156 } elseif ( $to && in_array( $v, $variants ) ) {
1157 $unidtable[$v][$from] = $to;
1160 // syntax error, pass
1161 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1162 $bidtable = array();
1163 $unidtable = array();
1167 $this->mBidtable
= $bidtable;
1168 $this->mUnidtable
= $unidtable;
1174 function getRulesDesc() {
1175 $codesep = $this->mConverter
->mDescCodeSep
;
1176 $varsep = $this->mConverter
->mDescVarSep
;
1178 foreach ( $this->mBidtable
as $k => $v ) {
1179 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1181 foreach ( $this->mUnidtable
as $k => $a ) {
1182 foreach ( $a as $from => $to ) {
1183 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1184 "$codesep$to$varsep";
1191 * Parse rules conversion.
1194 function getRuleConvertedStr( $variant ) {
1195 $bidtable = $this->mBidtable
;
1196 $unidtable = $this->mUnidtable
;
1198 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1199 return $this->mRules
;
1201 // display current variant in bidirectional array
1202 $disp = $this->getTextInBidtable( $variant );
1203 // or display current variant in fallbacks
1205 $disp = $this->getTextInBidtable(
1206 $this->mConverter
->getVariantFallbacks( $variant ) );
1208 // or display current variant in unidirectional array
1209 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1210 $disp = array_values( $unidtable[$variant] );
1213 // or display frist text under disable manual convert
1215 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1216 if ( count( $bidtable ) > 0 ) {
1217 $disp = array_values( $bidtable );
1220 $disp = array_values( $unidtable );
1221 $disp = array_values( $disp[0] );
1230 * Generate conversion table for all text.
1233 function generateConvTable() {
1234 // Special case optimisation
1235 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1236 $this->mConvTable
= array();
1240 $bidtable = $this->mBidtable
;
1241 $unidtable = $this->mUnidtable
;
1242 $manLevel = $this->mConverter
->mManualLevel
;
1245 foreach ( $this->mConverter
->mVariants
as $v ) {
1246 /* for bidirectional array
1247 fill in the missing variants, if any,
1249 if ( !isset( $bidtable[$v] ) ) {
1251 $this->mConverter
->getVariantFallbacks( $v );
1252 $vf = $this->getTextInBidtable( $variantFallbacks );
1254 $bidtable[$v] = $vf;
1258 if ( isset( $bidtable[$v] ) ) {
1259 foreach ( $vmarked as $vo ) {
1260 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1261 // or -{H|zh:WordZh;zh-tw:WordTw}-
1262 // or -{-|zh:WordZh;zh-tw:WordTw}-
1263 // to introduce a custom mapping between
1264 // words WordZh and WordTw in the whole text
1265 if ( $manLevel[$v] == 'bidirectional' ) {
1266 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1268 if ( $manLevel[$vo] == 'bidirectional' ) {
1269 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1274 /*for unidirectional array fill to convert tables */
1275 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1276 && isset( $unidtable[$v] ) )
1278 if ( isset( $this->mConvTable
[$v] ) ) {
1279 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1281 $this->mConvTable
[$v] = $unidtable[$v];
1288 * Parse rules and flags.
1291 function parse( $variant = NULL ) {
1293 $variant = $this->mConverter
->getPreferredVariant();
1296 $variants = $this->mConverter
->mVariants
;
1297 $this->parseFlags();
1298 $flags = $this->mFlags
;
1300 // convert to specified variant
1301 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1302 if ( $this->mVariantFlags
) {
1303 // check if current variant in flags
1304 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1305 // then convert <text to convert> to current language
1306 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1308 } else { // if current variant no in flags,
1309 // then we check its fallback variants.
1311 $this->mConverter
->getVariantFallbacks( $variant );
1312 foreach ( $variantFallbacks as $variantFallback ) {
1313 // if current variant's fallback exist in flags
1314 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1315 // then convert <text to convert> to fallback language
1317 $this->mConverter
->autoConvert( $this->mRules
,
1323 $this->mFlags
= $flags = array( 'R' => true );
1326 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1327 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1328 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1329 $this->parseRules();
1331 $rules = $this->mRules
;
1333 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1334 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1335 // fill all variants if text in -{A/H/-|text} without rules
1336 foreach ( $this->mConverter
->mVariants
as $v ) {
1337 $this->mBidtable
[$v] = $rules;
1339 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1340 $this->mFlags
= $flags = array( 'R' => true );
1344 $this->mRuleDisplay
= false;
1345 foreach ( $flags as $flag => $unused ) {
1348 // if we don't do content convert, still strip the -{}- tags
1349 $this->mRuleDisplay
= $rules;
1352 // process N flag: output current variant name
1353 $ruleVar = trim( $rules );
1354 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1355 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1357 $this->mRuleDisplay
= '';
1361 // process D flag: output rules description
1362 $this->mRuleDisplay
= $this->getRulesDesc();
1365 // process H,- flag or T only: output nothing
1366 $this->mRuleDisplay
= '';
1369 $this->mRulesAction
= 'remove';
1370 $this->mRuleDisplay
= '';
1373 $this->mRulesAction
= 'add';
1374 $this->mRuleDisplay
= '';
1377 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1380 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1381 $this->mRuleDisplay
= '';
1384 // ignore unknown flags (but see error case below)
1387 if ( $this->mRuleDisplay
=== false ) {
1388 $this->mRuleDisplay
= $this->mManualCodeError
;
1391 $this->generateConvTable();
1397 function hasRules() {
1402 * Get display text on markup -{...}-
1405 function getDisplay() {
1406 return $this->mRuleDisplay
;
1410 * Get converted title.
1413 function getTitle() {
1414 return $this->mRuleTitle
;
1418 * Return how deal with conversion rules.
1421 function getRulesAction() {
1422 return $this->mRulesAction
;
1426 * Get conversion table. ( bidirectional and unidirectional
1427 * conversion table )
1430 function getConvTable() {
1431 return $this->mConvTable
;
1435 * Get conversion rules string.
1438 function getRules() {
1439 return $this->mRules
;
1443 * Get conversion flags.
1446 function getFlags() {
1447 return $this->mFlags
;