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 convert
15 * @author Zhengzhu Feng <zhengzhu@gmail.com>
16 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>
18 class LanguageConverter
{
19 var $mPreferredVariant='';
20 var $mMainLanguageCode;
21 var $mVariants, $mVariantFallbacks, $mVariantNames;
22 var $mTablesLoaded = false;
24 var $mTitleDisplay='';
25 var $mDoTitleConvert=true, $mDoContentConvert=true;
26 var $mManualLevel; // 'bidirectional' 'unidirectional' 'disable' for each variants
27 var $mTitleFromFlag = false;
32 var $mDescCodeSep = ':',$mDescVarSep = ';';
33 var $mUcfirst = false;
35 const CACHE_VERSION_KEY
= 'VERSION 6';
40 * @param string $maincode the main language code of this language
41 * @param array $variants the supported variants of this language
42 * @param array $variantfallback the fallback language of each variant
43 * @param array $markup array defining the markup used for manual conversion
44 * @param array $flags array defining the custom strings that maps to the flags
47 function __construct($langobj, $maincode,
49 $variantfallbacks=array(),
52 $manualLevel = array() ) {
53 $this->mLangObj
= $langobj;
54 $this->mMainLanguageCode
= $maincode;
55 $this->mVariants
= $variants;
56 $this->mVariantFallbacks
= $variantfallbacks;
57 global $wgLanguageNames;
58 $this->mVariantNames
= $wgLanguageNames;
59 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
63 'unidsep'=>'=>', //for unidirectional conversion
68 $this->mMarkup
= array_merge($m, $markup);
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 (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 $this->mManualLevel
[$v]=array_key_exists($v,$manualLevel)
92 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 string $v the language code of the variant
104 * @return string array the code of the fallback language or false if there is no fallback
107 function getVariantFallbacks($v) {
108 if( isset( $this->mVariantFallbacks
[$v] ) ) {
109 return $this->mVariantFallbacks
[$v];
111 return $this->mMainLanguageCode
;
115 * get preferred language variants.
116 * @param boolean $fromUser Get it from $wgUser's preferences
117 * @return string the preferred language code
120 function getPreferredVariant( $fromUser = true ) {
121 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
123 if($this->mPreferredVariant
)
124 return $this->mPreferredVariant
;
126 // see if the preference is set in the request
127 $req = $wgRequest->getText( 'variant' );
128 if( in_array( $req, $this->mVariants
) ) {
129 $this->mPreferredVariant
= $req;
133 // check the syntax /code/ArticleTitle
134 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
135 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
136 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
137 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
138 if(in_array($scriptBase,$this->mVariants
)){
139 $this->mPreferredVariant
= $scriptBase;
140 return $this->mPreferredVariant
;
144 // get language variant preference from logged in users
145 // Don't call this on stub objects because that causes infinite
146 // recursion during initialisation
147 if( $fromUser && $wgUser->isLoggedIn() ) {
148 $this->mPreferredVariant
= $wgUser->getOption('variant');
149 return $this->mPreferredVariant
;
152 // see if default variant is globaly set
153 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
154 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
155 return $this->mPreferredVariant
;
158 # FIXME rewrite code for parsing http header. The current code
159 # is written specific for detecting zh- variants
160 if( !$this->mPreferredVariant
) {
161 // see if some supported language variant is set in the
162 // http header, but we don't set the mPreferredVariant
163 // variable in case this is called before the user's
164 // preference is loaded
165 $pv=$this->mMainLanguageCode
;
166 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
167 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
168 $zh = strstr($header, $pv.'-');
170 $pv = substr($zh,0,5);
173 // don't try to return bad variant
174 if(in_array( $pv, $this->mVariants
))
178 return $this->mMainLanguageCode
;
183 * dictionary-based conversion
185 * @param string $text the text to be converted
186 * @param string $toVariant the target language code
187 * @return string the converted text
190 function autoConvert($text, $toVariant=false) {
191 $fname="LanguageConverter::autoConvert";
193 wfProfileIn( $fname );
195 if(!$this->mTablesLoaded
)
199 $toVariant = $this->getPreferredVariant();
200 if(!in_array($toVariant, $this->mVariants
))
203 /* we convert everything except:
204 1. html markups (anything between < and >)
206 3. place holders created by the parser
209 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
210 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
214 // this one is needed when the text is inside an html markup
215 $htmlfix = '|<[^>]+$|^[^<>]*>';
217 // disable convert to variants between <code></code> tags
218 $codefix = '<code>.+?<\/code>|';
219 // disable convertsion of <script type="text/javascript"> ... </script>
220 $scriptfix = '<script.*?>.*?<\/script>|';
221 // disable conversion of <pre xxxx> ... </pre>
222 $prefix = '<pre.*?>.*?<\/pre>|';
224 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
226 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
228 $m = array_shift($matches);
230 $ret = $this->translate($m[0], $toVariant);
231 $mstart = $m[1]+
strlen($m[0]);
232 foreach($matches as $m) {
233 $ret .= substr($text, $mstart, $m[1]-$mstart);
234 $ret .= $this->translate($m[0], $toVariant);
235 $mstart = $m[1] +
strlen($m[0]);
237 wfProfileOut( $fname );
242 * Translate a string to a variant
243 * Doesn't process markup or do any of that other stuff, for that use convert()
245 * @param string $text Text to convert
246 * @param string $variant Variant language code
247 * @return string Translated text
250 function translate( $text, $variant ) {
251 wfProfileIn( __METHOD__
);
252 if( !$this->mTablesLoaded
)
254 $text = $this->mTables
[$variant]->replace( $text );
255 wfProfileOut( __METHOD__
);
260 * convert text to all supported variants
262 * @param string $text the text to be converted
263 * @return array of string
266 function autoConvertToAllVariants($text) {
267 $fname="LanguageConverter::autoConvertToAllVariants";
268 wfProfileIn( $fname );
269 if( !$this->mTablesLoaded
)
273 foreach($this->mVariants
as $variant) {
274 $ret[$variant] = $this->translate($text, $variant);
277 wfProfileOut( $fname );
282 * convert link text to all supported variants
284 * @param string $text the text to be converted
285 * @return array of string
288 function convertLinkToAllVariants($text) {
289 if( !$this->mTablesLoaded
)
293 $tarray = explode($this->mMarkup
['begin'], $text);
294 $tfirst = array_shift($tarray);
296 foreach($this->mVariants
as $variant)
297 $ret[$variant] = $this->translate($tfirst,$variant);
299 foreach($tarray as $txt) {
300 $marked = explode($this->mMarkup
['end'], $txt, 2);
302 foreach($this->mVariants
as $variant){
303 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
304 if(array_key_exists(1, $marked))
305 $ret[$variant] .= $this->translate($marked[1],$variant);
315 * apply manual conversion
318 function applyManualConv($convRule){
319 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
320 $title = $convRule->getTitle();
322 $this->mTitleFromFlag
= true;
323 $this->mTitleDisplay
= $title;
326 //add manual conversion table to global table
327 $convTable = $convRule->getConvTable();
328 $isAdd = $convRule->getRulesAction()=="add";
329 $isRemove = $convRule->getRulesAction()=="remove";
330 foreach($convTable as $v=>$t) {
331 if( !in_array($v,$this->mVariants
) )continue;
333 $this->mTables
[$v]->mergeArray($t);
335 $this->mTables
[$v]->removeArray($t);
340 * Convert text using a parser object for context
343 function parserConvert( $text, &$parser ) {
344 global $wgDisableLangConversion;
345 /* don't do anything if this is the conversion table */
346 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
347 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
352 if($wgDisableLangConversion)
355 $text = $this->convert( $text );
356 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
364 function convertTitle($text){
365 // check for __NOTC__ tag
366 if( !$this->mDoTitleConvert
) {
367 $this->mTitleDisplay
= $text;
371 // use the title from the T flag if any
372 if($this->mTitleFromFlag
){
373 $this->mTitleFromFlag
= false;
374 return $this->mTitleDisplay
;
378 $isredir = $wgRequest->getText( 'redirect', 'yes' );
379 $action = $wgRequest->getText( 'action' );
380 if ( $isredir == 'no' ||
$action == 'edit' ) {
383 $this->mTitleDisplay
= $this->convert($text);
384 return $this->mTitleDisplay
;
389 * convert text to different variants of a language. the automatic
390 * conversion is done in autoConvert(). here we parse the text
391 * marked with -{}-, which specifies special conversions of the
392 * text that can not be accomplished in autoConvert()
394 * syntax of the markup:
395 * -{code1:text1;code2:text2;...}- or
396 * -{flags|code1:text1;code2:text2;...}- or
397 * -{text}- in which case no conversion should take place for text
399 * @param string $text text to be converted
400 * @param bool $isTitle whether this conversion is for the article title
401 * @return string converted text
404 function convert( $text , $isTitle=false) {
406 $mw =& MagicWord
::get( 'notitleconvert' );
407 if( $mw->matchAndRemove( $text ) )
408 $this->mDoTitleConvert
= false;
409 $mw =& MagicWord
::get( 'nocontentconvert' );
410 if( $mw->matchAndRemove( $text ) ) {
411 $this->mDoContentConvert
= false;
414 // no conversion if redirecting
415 $mw =& MagicWord
::get( 'redirect' );
416 if( $mw->matchStart( $text ))
419 // for title convertion
420 if ($isTitle) return $this->convertTitle($text);
422 $plang = $this->getPreferredVariant();
423 $tarray = explode($this->mMarkup
['end'], $text);
425 foreach($tarray as $txt) {
426 $marked = explode($this->mMarkup
['begin'], $txt, 2);
428 if( $this->mDoContentConvert
)
429 $text .= $this->autoConvert($marked[0],$plang);
433 if(array_key_exists(1, $marked)){
434 // strip the flags from syntax like -{T| ... }-
435 $crule = new ConverterRule($marked[1], $this);
436 $crule->parse($plang);
438 $text .= $crule->getDisplay();
439 $this->applyManualConv($crule);
447 * if a language supports multiple variants, it is
448 * possible that non-existing link in one variant
449 * actually exists in another variant. this function
450 * tries to find it. See e.g. LanguageZh.php
452 * @param string $link the name of the link
453 * @param mixed $nt the title object of the link
454 * @return null the input parameters may be modified upon return
457 function findVariantLink( &$link, &$nt ) {
458 global $wgDisableLangConversion;
459 $linkBatch = new LinkBatch();
464 $ns = $nt->getNamespace();
466 $variants = $this->autoConvertToAllVariants($link);
467 if($variants == false) //give up
472 foreach( $variants as $v ) {
474 $varnt = Title
::newFromText( $v, $ns );
475 if(!is_null($varnt)){
476 $linkBatch->addObj($varnt);
482 // fetch all variants in single query
483 $linkBatch->execute();
485 foreach( $titles as $varnt ) {
486 if( $varnt->getArticleID() > 0 ) {
488 if( !$wgDisableLangConversion )
496 * returns language specific hash options
500 function getExtraHashOptions() {
501 $variant = $this->getPreferredVariant();
502 return '!' . $variant ;
506 * get title text as defined in the body of the article text
510 function getParsedTitle() {
511 return $this->mTitleDisplay
;
515 * a write lock to the cache
519 function lockCache() {
522 for($i=0; $i<30; $i++
) {
523 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
535 function unlockCache() {
537 $wgMemc->delete($this->mCacheKey
. "lock");
542 * Load default conversion tables
543 * This method must be implemented in derived class
547 function loadDefaultTables() {
548 $name = get_class($this);
549 wfDie("Must implement loadDefaultTables() method in class $name");
553 * load conversion tables either from the cache or the disk
556 function loadTables($fromcache=true) {
558 if( $this->mTablesLoaded
)
560 wfProfileIn( __METHOD__
);
561 $this->mTablesLoaded
= true;
562 $this->mTables
= false;
564 wfProfileIn( __METHOD__
.'-cache' );
565 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
566 wfProfileOut( __METHOD__
.'-cache' );
568 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
569 wfProfileIn( __METHOD__
.'-recache' );
570 // not in cache, or we need a fresh reload.
571 // we will first load the default tables
572 // then update them using things in MediaWiki:Zhconversiontable/*
573 $this->loadDefaultTables();
574 foreach($this->mVariants
as $var) {
575 $cached = $this->parseCachedTable($var);
576 $this->mTables
[$var]->mergeArray($cached);
579 $this->postLoadTables();
580 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
582 if($this->lockCache()) {
583 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
584 $this->unlockCache();
586 wfProfileOut( __METHOD__
.'-recache' );
588 wfProfileOut( __METHOD__
);
592 * Hook for post processig after conversion tables are loaded
595 function postLoadTables() {}
598 * Reload the conversion tables
602 function reloadTables() {
604 unset($this->mTables
);
605 $this->mTablesLoaded
= false;
606 $this->loadTables(false);
611 * parse the conversion table stored in the cache
613 * the tables should be in blocks of the following form:
620 * to make the tables more manageable, subpages are allowed
621 * and will be parsed recursively if $recursive=true
624 function parseCachedTable($code, $subpage='', $recursive=true) {
625 global $wgMessageCache;
626 static $parsed = array();
628 if(!is_object($wgMessageCache))
631 $key = 'Conversiontable/'.$code;
633 $key .= '/' . $subpage;
635 if(array_key_exists($key, $parsed))
638 if ( strpos( $code, '/' ) === false ) {
639 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
641 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
642 if ( $title && $title->exists() ) {
643 $article = new Article( $title );
644 $txt = $article->getContents();
650 // get all subpage links of the form
651 // [[MediaWiki:conversiontable/zh-xx/...|...]]
652 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
653 $subs = explode('[[', $txt);
655 foreach( $subs as $sub ) {
656 $link = explode(']]', $sub, 2);
657 if(count($link) != 2)
659 $b = explode('|', $link[0]);
660 $b = explode('/', trim($b[0]), 3);
666 if($b[0] == $linkhead && $b[1] == $code) {
667 $sublinks[] = $sublink;
672 // parse the mappings in this page
673 $blocks = explode($this->mMarkup
['begin'], $txt);
674 array_shift($blocks);
676 foreach($blocks as $block) {
677 $mappings = explode($this->mMarkup
['end'], $block, 2);
678 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
679 $table = explode( ';', $stripped );
680 foreach( $table as $t ) {
681 $m = explode( '=>', $t );
682 if( count( $m ) != 2)
684 // trim any trailling comments starting with '//'
685 $tt = explode('//', $m[1], 2);
686 $ret[trim($m[0])] = trim($tt[0]);
689 $parsed[$key] = true;
692 // recursively parse the subpages
694 foreach($sublinks as $link) {
695 $s = $this->parseCachedTable($code, $link, $recursive);
696 $ret = array_merge($ret, $s);
700 if ($this->mUcfirst
) {
701 foreach ($ret as $k => $v) {
702 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
709 * Enclose a string with the "no conversion" tag. This is used by
710 * various functions in the Parser
712 * @param string $text text to be tagged for no conversion
713 * @return string the tagged text
716 function markNoConversion($text, $noParse=false) {
717 # don't mark if already marked
718 if(strpos($text, $this->mMarkup
['begin']) ||
719 strpos($text, $this->mMarkup
['end']))
722 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
727 * convert the sorting key for category links. this should make different
728 * keys that are variants of each other map to the same key
730 function convertCategoryKey( $key ) {
734 * hook to refresh the cache of conversion tables when
735 * MediaWiki:conversiontable* is updated
738 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
739 $titleobj = $article->getTitle();
740 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
741 $title = $titleobj->getDBkey();
742 $t = explode('/', $title, 3);
744 if( $c > 1 && $t[0] == 'Conversiontable' ) {
745 if(in_array($t[1], $this->mVariants
)) {
746 $this->reloadTables();
754 * Armour rendered math against conversion
755 * Wrap math into rawoutput -{R| math }- syntax
758 function armourMath($text){
759 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
765 * parser for rules of language conversion , parse rules in -{ }- tag
767 * @author fdcn <fdcn64@gmail.com>
769 class ConverterRule
{
770 var $mText; // original text in -{text}-
771 var $mConverter; // LanguageConverter object
772 var $mManualCodeError='<strong class="error">code error!</strong>';
773 var $mRuleDisplay = '',$mRuleTitle=false;
774 var $mRules = '';// string : the text of the rules
775 var $mRulesAction = 'none';
776 var $mFlags = array();
777 var $mConvTable = array();
778 var $mBidtable = array();// array of the translation in each variant
779 var $mUnidtable = array();// array of the translation in each variant
784 * @param string $text the text between -{ and }-
785 * @param object $converter a LanguageConverter object
788 function __construct($text,$converter){
789 $this->mText
= $text;
790 $this->mConverter
=$converter;
791 foreach($converter->mVariants
as $v){
792 $this->mConvTable
[$v]=array();
797 * check if variants array in convert array
799 * @param string $variant Variant language code
800 * @return string Translated text
803 function getTextInBidtable($variants){
804 if(is_string($variants)){ $variants=array($variants); }
805 if(!is_array($variants)) return false;
806 foreach ($variants as $variant){
807 if(array_key_exists($variant, $this->mBidtable
)){
808 return $this->mBidtable
[$variant];
815 * Parse flags with syntax -{FLAG| ... }-
818 function parseFlags(){
819 $text = $this->mText
;
820 if(strlen($text) < 2 ) {
821 $this->mFlags
= array( 'R' );
822 $this->mRules
= $text;
827 $markup = $this->mConverter
->mMarkup
;
828 $validFlags = $this->mConverter
->mFlags
;
830 $tt = explode($markup['flagsep'], $text, 2);
831 if(count($tt) == 2) {
832 $f = explode($markup['varsep'], $tt[0]);
835 if(array_key_exists($ff, $validFlags) &&
836 !in_array($validFlags[$ff], $flags))
837 $flags[] = $validFlags[$ff];
844 if( !in_array('R',$flags) ){
845 //FIXME: may cause trouble here...
846 //strip since it interferes with the parsing, plus,
847 //all spaces should be stripped in this tag anyway.
848 $rules = str_replace(' ', '', $rules);
849 $rules = str_replace('=>','=>',$rules);
853 if( in_array('R',$flags) ){
854 $flags = array('R');// remove other flags
855 } elseif ( in_array('N',$flags) ){
856 $flags = array('N');// remove other flags
857 } elseif ( in_array('-',$flags) ){
858 $flags = array('-');// remove other flags
859 } elseif (count($flags)==1 && $flags[0]=='T'){
861 } elseif ( in_array('H',$flags) ){
862 // replace A flag, and remove other flags except T
863 $temp=array('+','H');
864 if(in_array('T',$flags)) $temp[] = 'T';
865 if(in_array('D',$flags)) $temp[] = 'D';
868 if ( in_array('A',$flags)) {
872 if ( in_array('D',$flags) )
873 $flags=array_diff($flags,array('S'));
875 if ( count($flags)==0 )
877 $this->mRules
=$rules;
878 $this->mFlags
=$flags;
882 * generate conversion table
885 function parseRules() {
886 $rules = $this->mRules
;
887 $flags = $this->mFlags
;
889 $unidtable = array();
890 $markup = $this->mConverter
->mMarkup
;
892 $choice = explode($markup['varsep'], $rules );
893 foreach($choice as $c) {
894 $v = explode($markup['codesep'], $c);
896 continue;// syntax error, skip
899 $u = explode($markup['unidsep'], $v);
902 } else if(count($u) == 2){
903 $from=trim($u[0]);$v=trim($u[1]);
904 if( array_key_exists($v,$unidtable) && !is_array($unidtable[$v]) )
905 $unidtable[$v]=array($from=>$to);
907 $unidtable[$v][$from]=$to;
909 // syntax error, pass
910 if (!array_key_exists($v,$this->mConverter
->mVariantNames
)){
912 $unidtable = array();
916 $this->mBidtable
= $bidtable;
917 $this->mUnidtable
= $unidtable;
923 function getRulesDesc(){
924 $codesep = $this->mConverter
->mDescCodeSep
;
925 $varsep = $this->mConverter
->mDescVarSep
;
927 foreach($this->mBidtable
as $k => $v)
928 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
929 foreach($this->mUnidtable
as $k => $a)
930 foreach($a as $from=>$to)
931 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
936 * Parse rules conversion
939 function getRuleConvertedStr($variant,$doConvert){
940 $bidtable = $this->mBidtable
;
941 $unidtable = $this->mUnidtable
;
943 if( count($bidtable) +
count($unidtable) == 0 ){
944 return $this->mRules
;
945 } elseif ($doConvert){// the text converted
946 // display current variant in bidirectional array
947 $disp = $this->getTextInBidtable($variant);
948 // or display current variant in fallbacks
950 $disp = $this->getTextInBidtable(
951 $this->mConverter
->getVariantFallbacks($variant));
952 // or display current variant in unidirectional array
953 if(!$disp && array_key_exists($variant,$unidtable)){
954 $disp = array_values($unidtable[$variant]);
957 // or display frist text under disable manual convert
958 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
959 if(count($bidtable)>0){
960 $disp = array_values($bidtable);
963 $disp = array_values($unidtable);
964 $disp = array_values($disp[0]);
969 } else {// no convert
970 return $this->mRules
;
975 * generate conversion table for all text
978 function generateConvTable(){
979 //$rules = $this->mRules;
980 $flags = $this->mFlags
;
981 $bidtable = $this->mBidtable
;
982 $unidtable = $this->mUnidtable
;
983 $manLevel = $this->mConverter
->mManualLevel
;
986 foreach($this->mConverter
->mVariants
as $v) {
987 /* for bidirectional array
988 fill in the missing variants, if any,
990 if(!array_key_exists($v, $bidtable)) {
991 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
992 $vf = $this->getTextInBidtable($variantFallbacks);
993 if($vf) $bidtable[$v] = $vf;
996 if(array_key_exists($v,$bidtable)){
997 foreach($vmarked as $vo){
998 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
999 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1000 // to introduce a custom mapping between
1001 // words WordZh and WordTw in the whole text
1002 if($manLevel[$v]=='bidirectional'){
1003 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1005 if($manLevel[$vo]=='bidirectional'){
1006 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1011 /*for unidirectional array
1012 fill to convert tables */
1013 $allow_unid = $manLevel[$v]=='bidirectional'
1014 ||
$manLevel[$v]=='unidirectional';
1015 if($allow_unid && array_key_exists($v,$unidtable)){
1016 $ct=$this->mConvTable
[$v];
1017 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1023 * Parse rules and flags
1026 function parse($variant){
1027 if(!$variant) $variant = $this->mConverter
->getPreferredVariant();
1029 $this->parseFlags();
1030 $this->parseRules();
1032 $rules = $this->mRules
;
1033 $flags = $this->mFlags
;
1035 if(count($this->mBidtable
)==0 && count($this->mUnidtable
)==0){
1036 if(in_array('+',$flags) ||
in_array('-',$flags))
1037 // fill all variants if text in -{A/H/-|text} without rules
1038 foreach($this->mConverter
->mVariants
as $v)
1039 $this->mBidtable
[$v] = $rules;
1040 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1041 $this->mFlags
= $flags = array('R');
1044 if( in_array('R',$flags) ) {
1045 // if we don't do content convert, still strip the -{}- tags
1046 $this->mRuleDisplay
= $rules;
1047 } elseif ( in_array('N',$flags) ){
1048 // proces N flag: output current variant name
1049 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1050 } elseif ( in_array('D',$flags) ){
1051 // proces D flag: output rules description
1052 $this->mRuleDisplay
= $this->getRulesDesc();
1053 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1054 // proces H,- flag or T only: output nothing
1055 $this->mRuleDisplay
= '';
1056 } elseif ( in_array('S',$flags) ){
1057 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1058 $this->mConverter
->mDoContentConvert
);
1060 $this->mRuleDisplay
= $this->mManualCodeError
;
1062 // proces T flag : output nothing
1063 if ( in_array('T',$flags) ) {
1064 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1065 $this->mConverter
->mDoTitleConvert
);
1068 if (in_array('-', $flags))
1069 $this->mRulesAction
='remove';
1070 if (in_array('+', $flags))
1071 $this->mRulesAction
='add';
1073 $this->generateConvTable();
1079 function hasRules(){
1084 * get display text on markup -{...}-
1085 * @param string $variant the current variant
1088 function getDisplay(){
1089 return $this->mRuleDisplay
;
1092 * get converted title
1093 * @param string $variant the current variant
1096 function getTitle(){
1097 return $this->mRuleTitle
;
1101 * return how deal with conversion rules
1104 function getRulesAction(){
1105 return $this->mRulesAction
;
1109 * get conversion table ( bidirectional and unidirectional conversion table )
1112 function getConvTable(){
1113 return $this->mConvTable
;
1117 * get conversion rules string
1120 function getRules(){
1121 return $this->mRules
;
1125 * get conversion flags
1128 function getFlags(){
1129 return $this->mFlags
;