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>, PhiLiP <philip.npc@gmail.com>
18 class LanguageConverter
{
19 var $mPreferredVariant='';
20 var $mMainLanguageCode;
21 var $mVariants, $mVariantFallbacks, $mLanguageNames;
22 var $mTablesLoaded = false;
24 var $mManualAddTables;
25 var $mManualRemoveTables;
26 var $mTitleDisplay='';
27 var $mDoTitleConvert=true, $mDoContentConvert=true;
28 var $mManualLevel; // 'bidirectional' 'unidirectional' 'disable' for each variants
29 var $mTitleFromFlag = false;
34 var $mDescCodeSep = ':',$mDescVarSep = ';';
35 var $mUcfirst = false;
37 const CACHE_VERSION_KEY
= 'VERSION 6';
42 * @param string $maincode the main language code of this language
43 * @param array $variants the supported variants of this language
44 * @param array $variantfallback the fallback language of each variant
45 * @param array $markup array defining the markup used for manual conversion
46 * @param array $flags array defining the custom strings that maps to the flags
47 * @param array $manualLevel limit for supported variants
50 function __construct($langobj, $maincode,
52 $variantfallbacks=array(),
55 $manualLevel = array() ) {
56 $this->mLangObj
= $langobj;
57 $this->mMainLanguageCode
= $maincode;
58 $this->mVariants
= $variants;
59 $this->mVariantFallbacks
= $variantfallbacks;
60 global $wgLanguageNames;
61 $this->mLanguageNames
= $wgLanguageNames;
62 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
66 'unidsep'=>'=>', //for unidirectional conversion
71 $this->mMarkup
= array_merge($m, $markup);
73 // 'S' show converted text
74 // '+' add rules for alltext
75 // 'E' the gave flags is error
76 // these flags above are reserved for program
77 'A'=>'A', // add rule for convert code (all text convert)
78 'T'=>'T', // title convert
79 'R'=>'R', // raw content
80 'D'=>'D', // convert description (subclass implement)
81 '-'=>'-', // remove convert (not implement)
82 'H'=>'H', // add rule for convert code (but no display in placed code )
83 'N'=>'N' // current variant name
85 $this->mFlags
= array_merge($f, $flags);
86 foreach( $this->mVariants
as $v) {
87 $this->mManualLevel
[$v]=array_key_exists($v,$manualLevel)
90 $this->mManualAddTables
[$v] = array();
91 $this->mManualRemoveTables
[$v] = array();
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 string $v the language code of the variant
110 * @return string array the code of the fallback language or false if there is no fallback
113 function getVariantFallbacks($v) {
114 if( isset( $this->mVariantFallbacks
[$v] ) ) {
115 return $this->mVariantFallbacks
[$v];
117 return $this->mMainLanguageCode
;
120 // this method body in Language class
121 function getPreferredVariant( $fromUser = true ) {
122 return $this->mLangObj
->getPreferredVariant( $fromUser );
126 * caption convert, base on preg_replace_callback
128 * to convert text in "title" or "alt", like '<img alt="text" ... '
129 * or '<span title="text" ... '
131 * @return string like ' alt="yyyy"' or ' title="yyyy"'
134 function captionConvert( $matches ) {
135 $toVariant = $this->getPreferredVariant();
136 $title = $matches[1];
138 // we convert captions except URL
139 if( !strpos( $text, '://' ) )
140 $text = $this->translate($text, $toVariant);
141 return " $title=\"$text\"";
145 * dictionary-based conversion
147 * @param string $text the text to be converted
148 * @param string $toVariant the target language code
149 * @return string the converted text
152 function autoConvert($text, $toVariant=false) {
153 $fname="LanguageConverter::autoConvert";
155 wfProfileIn( $fname );
157 if(!$this->mTablesLoaded
)
161 $toVariant = $this->getPreferredVariant();
162 if(!in_array($toVariant, $this->mVariants
))
165 /* we convert everything except:
166 1. html markups (anything between < and >)
168 3. place holders created by the parser
171 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
172 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
176 // this one is needed when the text is inside an html markup
177 $htmlfix = '|<[^>]+$|^[^<>]*>';
179 // disable convert to variants between <code></code> tags
180 $codefix = '<code>.+?<\/code>|';
181 // disable convertsion of <script type="text/javascript"> ... </script>
182 $scriptfix = '<script.*?>.*?<\/script>|';
183 // disable conversion of <pre xxxx> ... </pre>
184 $prefix = '<pre.*?>.*?<\/pre>|';
186 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
188 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
190 $m = array_shift($matches);
192 $ret = $this->translate($m[0], $toVariant);
193 $mstart = $m[1]+
strlen($m[0]);
195 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
196 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
197 foreach($matches as $m) {
198 $mark = substr($text, $mstart, $m[1]-$mstart);
199 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
201 $ret .= $this->translate($m[0], $toVariant);
202 $mstart = $m[1] +
strlen($m[0]);
204 wfProfileOut( $fname );
209 * Translate a string to a variant
210 * Doesn't process markup or do any of that other stuff, for that use convert()
212 * @param string $text Text to convert
213 * @param string $variant Variant language code
214 * @return string Translated text
217 function translate( $text, $variant ) {
218 wfProfileIn( __METHOD__
);
219 if( !$this->mTablesLoaded
)
221 $text = $this->mTables
[$variant]->replace( $text );
222 wfProfileOut( __METHOD__
);
227 * convert text to all supported variants
229 * @param string $text the text to be converted
230 * @return array of string
233 function autoConvertToAllVariants($text) {
234 $fname="LanguageConverter::autoConvertToAllVariants";
235 wfProfileIn( $fname );
236 if( !$this->mTablesLoaded
)
240 foreach($this->mVariants
as $variant) {
241 $ret[$variant] = $this->translate($text, $variant);
244 wfProfileOut( $fname );
249 * convert link text to all supported variants
251 * @param string $text the text to be converted
252 * @return array of string
255 function convertLinkToAllVariants($text) {
256 if( !$this->mTablesLoaded
)
260 $tarray = explode($this->mMarkup
['begin'], $text);
261 $tfirst = array_shift($tarray);
263 foreach($this->mVariants
as $variant)
264 $ret[$variant] = $this->translate($tfirst,$variant);
266 foreach($tarray as $txt) {
267 $marked = explode($this->mMarkup
['end'], $txt, 2);
269 foreach($this->mVariants
as $variant){
270 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
271 if(array_key_exists(1, $marked))
272 $ret[$variant] .= $this->translate($marked[1],$variant);
281 * prepare manual conversion table
284 function prepareManualConv($convRule){
285 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
286 $title = $convRule->getTitle();
288 $this->mTitleFromFlag
= true;
289 $this->mTitleDisplay
= $title;
292 //apply manual conversion table to global table
293 $convTable = $convRule->getConvTable();
294 $action = $convRule->getRulesAction();
295 foreach($convTable as $v=>$t) {
296 if( !in_array($v,$this->mVariants
) )continue;
297 if( $action=="add" ) {
298 foreach($t as $from=>$to) {
299 // to ensure that $from and $to not be left blank
300 // so $this->translate() could always return a string
302 // more efficient than array_merge(), about 2.5 times.
303 $this->mManualAddTables
[$v][$from] = $to;
306 elseif ( $action=="remove" ) {
307 foreach($t as $from=>$to) {
309 $this->mManualRemoveTables
[$v][$from] = $to;
316 * apply manual conversion from $this->mManualAddTables and $this->mManualRemoveTables
319 function applyManualConv(){
320 //apply manual conversion table to global table
321 foreach($this->mVariants
as $v) {
322 if (count($this->mManualAddTables
[$v]) > 0) {
323 $this->mTables
[$v]->mergeArray($this->mManualAddTables
[$v]);
325 if (count($this->mManualRemoveTables
[$v]) > 0)
326 $this->mTables
[$v]->removeArray($this->mManualRemoveTables
[$v]);
331 * Convert text using a parser object for context
334 function parserConvert( $text, &$parser ) {
335 global $wgDisableLangConversion;
336 /* don't do anything if this is the conversion table */
337 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
338 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
343 if($wgDisableLangConversion)
346 $text = $this->convert( $text );
347 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
355 function convertTitle($text){
356 global $wgDisableTitleConversion, $wgUser;
358 // check for global param and __NOTC__ tag
359 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
$wgUser->getOption('noconvertlink') == 1 ) {
360 $this->mTitleDisplay
= $text;
364 // use the title from the T flag if any
365 if($this->mTitleFromFlag
){
366 $this->mTitleFromFlag
= false;
367 return $this->mTitleDisplay
;
371 $isredir = $wgRequest->getText( 'redirect', 'yes' );
372 $action = $wgRequest->getText( 'action' );
373 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
374 if ( $isredir == 'no' ||
$action == 'edit' ||
$action == 'submit' ||
$linkconvert == 'no' ) {
377 $this->mTitleDisplay
= $this->convert($text);
378 return $this->mTitleDisplay
;
383 * convert text to different variants of a language. the automatic
384 * conversion is done in autoConvert(). here we parse the text
385 * marked with -{}-, which specifies special conversions of the
386 * text that can not be accomplished in autoConvert()
388 * syntax of the markup:
389 * -{code1:text1;code2:text2;...}- or
390 * -{flags|code1:text1;code2:text2;...}- or
391 * -{text}- in which case no conversion should take place for text
393 * @param string $text text to be converted
394 * @param bool $isTitle whether this conversion is for the article title
395 * @return string converted text
398 function convert( $text , $isTitle=false) {
400 $mw =& MagicWord
::get( 'notitleconvert' );
401 if( $mw->matchAndRemove( $text ) )
402 $this->mDoTitleConvert
= false;
403 $mw =& MagicWord
::get( 'nocontentconvert' );
404 if( $mw->matchAndRemove( $text ) ) {
405 $this->mDoContentConvert
= false;
408 // no conversion if redirecting
409 $mw =& MagicWord
::get( 'redirect' );
410 if( $mw->matchStart( $text ))
413 // for title convertion
414 if ($isTitle) return $this->convertTitle($text);
416 $plang = $this->getPreferredVariant();
417 $tarray = StringUtils
::explode($this->mMarkup
['end'], $text);
421 foreach($tarray as $txt) {
422 $marked = explode($this->mMarkup
['begin'], $txt, 2);
423 if (array_key_exists(1, $marked)) {
424 $crule = new ConverterRule($marked[1], $this);
425 $crule->parse($plang);
426 $marked[1] = $crule->getDisplay();
427 $this->prepareManualConv($crule);
430 $marked[0] .= $this->mMarkup
['end'];
431 array_push($marks, $marked);
433 $this->applyManualConv();
434 foreach ($marks as $marked) {
435 if( $this->mDoContentConvert
)
436 $text .= $this->autoConvert($marked[0],$plang);
439 if( array_key_exists(1, $marked) )
442 // Remove the last delimiter (wasn't real)
443 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
449 * if a language supports multiple variants, it is
450 * possible that non-existing link in one variant
451 * actually exists in another variant. this function
452 * tries to find it. See e.g. LanguageZh.php
454 * @param string $link the name of the link
455 * @param mixed $nt the title object of the link
456 * @return null the input parameters may be modified upon return
459 function findVariantLink( &$link, &$nt, $forTemplate = false ) {
460 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
461 $isredir = $wgRequest->getText( 'redirect', 'yes' );
462 $action = $wgRequest->getText( 'action' );
463 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
464 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
465 $linkBatch = new LinkBatch();
469 if ( $disableLinkConversion ||
( !$forTemplate && ( $isredir == 'no' ||
$action == 'edit'
470 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) ) {
475 $ns = $nt->getNamespace();
477 $variants = $this->autoConvertToAllVariants($link);
478 if($variants == false) //give up
483 foreach( $variants as $v ) {
485 $varnt = Title
::newFromText( $v, $ns );
486 if(!is_null($varnt)){
487 $linkBatch->addObj($varnt);
493 // fetch all variants in single query
494 $linkBatch->execute();
496 foreach( $titles as $varnt ) {
497 if( $varnt->getArticleID() > 0 ) {
506 * returns language specific hash options
510 function getExtraHashOptions() {
511 $variant = $this->getPreferredVariant();
512 return '!' . $variant ;
516 * get title text as defined in the body of the article text
520 function getParsedTitle() {
521 return $this->mTitleDisplay
;
525 * a write lock to the cache
529 function lockCache() {
532 for($i=0; $i<30; $i++
) {
533 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
545 function unlockCache() {
547 $wgMemc->delete($this->mCacheKey
. "lock");
552 * Load default conversion tables
553 * This method must be implemented in derived class
557 function loadDefaultTables() {
558 $name = get_class($this);
559 wfDie("Must implement loadDefaultTables() method in class $name");
563 * load conversion tables either from the cache or the disk
566 function loadTables($fromcache=true) {
568 if( $this->mTablesLoaded
)
570 wfProfileIn( __METHOD__
);
571 $this->mTablesLoaded
= true;
572 $this->mTables
= false;
574 wfProfileIn( __METHOD__
.'-cache' );
575 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
576 wfProfileOut( __METHOD__
.'-cache' );
578 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
579 wfProfileIn( __METHOD__
.'-recache' );
580 // not in cache, or we need a fresh reload.
581 // we will first load the default tables
582 // then update them using things in MediaWiki:Zhconversiontable/*
583 $this->loadDefaultTables();
584 foreach($this->mVariants
as $var) {
585 $cached = $this->parseCachedTable($var);
586 $this->mTables
[$var]->mergeArray($cached);
589 $this->postLoadTables();
590 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
592 if($this->lockCache()) {
593 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
594 $this->unlockCache();
596 wfProfileOut( __METHOD__
.'-recache' );
598 wfProfileOut( __METHOD__
);
602 * Hook for post processig after conversion tables are loaded
605 function postLoadTables() {}
608 * Reload the conversion tables
612 function reloadTables() {
614 unset($this->mTables
);
615 $this->mTablesLoaded
= false;
616 $this->loadTables(false);
621 * parse the conversion table stored in the cache
623 * the tables should be in blocks of the following form:
630 * to make the tables more manageable, subpages are allowed
631 * and will be parsed recursively if $recursive=true
634 function parseCachedTable($code, $subpage='', $recursive=true) {
635 global $wgMessageCache;
636 static $parsed = array();
638 if(!is_object($wgMessageCache))
641 $key = 'Conversiontable/'.$code;
643 $key .= '/' . $subpage;
645 if(array_key_exists($key, $parsed))
648 if ( strpos( $code, '/' ) === false ) {
649 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
651 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
652 if ( $title && $title->exists() ) {
653 $article = new Article( $title );
654 $txt = $article->getContents();
660 // get all subpage links of the form
661 // [[MediaWiki:conversiontable/zh-xx/...|...]]
662 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
663 $subs = explode('[[', $txt);
665 foreach( $subs as $sub ) {
666 $link = explode(']]', $sub, 2);
667 if(count($link) != 2)
669 $b = explode('|', $link[0]);
670 $b = explode('/', trim($b[0]), 3);
676 if($b[0] == $linkhead && $b[1] == $code) {
677 $sublinks[] = $sublink;
682 // parse the mappings in this page
683 $blocks = explode($this->mMarkup
['begin'], $txt);
684 array_shift($blocks);
686 foreach($blocks as $block) {
687 $mappings = explode($this->mMarkup
['end'], $block, 2);
688 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
689 $table = explode( ';', $stripped );
690 foreach( $table as $t ) {
691 $m = explode( '=>', $t );
692 if( count( $m ) != 2)
694 // trim any trailling comments starting with '//'
695 $tt = explode('//', $m[1], 2);
696 $ret[trim($m[0])] = trim($tt[0]);
699 $parsed[$key] = true;
702 // recursively parse the subpages
704 foreach($sublinks as $link) {
705 $s = $this->parseCachedTable($code, $link, $recursive);
706 $ret = array_merge($ret, $s);
710 if ($this->mUcfirst
) {
711 foreach ($ret as $k => $v) {
712 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
719 * Enclose a string with the "no conversion" tag. This is used by
720 * various functions in the Parser
722 * @param string $text text to be tagged for no conversion
723 * @return string the tagged text
726 function markNoConversion($text, $noParse=false) {
727 # don't mark if already marked
728 if(strpos($text, $this->mMarkup
['begin']) ||
729 strpos($text, $this->mMarkup
['end']))
732 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
737 * convert the sorting key for category links. this should make different
738 * keys that are variants of each other map to the same key
740 function convertCategoryKey( $key ) {
744 * hook to refresh the cache of conversion tables when
745 * MediaWiki:conversiontable* is updated
748 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
749 $titleobj = $article->getTitle();
750 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
751 $title = $titleobj->getDBkey();
752 $t = explode('/', $title, 3);
754 if( $c > 1 && $t[0] == 'Conversiontable' ) {
755 if(in_array($t[1], $this->mVariants
)) {
756 $this->reloadTables();
764 * Armour rendered math against conversion
765 * Wrap math into rawoutput -{R| math }- syntax
768 function armourMath($text){
769 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
775 * parser for rules of language conversion , parse rules in -{ }- tag
777 * @author fdcn <fdcn64@gmail.com>
779 class ConverterRule
{
780 var $mText; // original text in -{text}-
781 var $mConverter; // LanguageConverter object
782 var $mManualCodeError='<strong class="error">code error!</strong>';
783 var $mRuleDisplay = '',$mRuleTitle=false;
784 var $mRules = '';// string : the text of the rules
785 var $mRulesAction = 'none';
786 var $mFlags = array();
787 var $mConvTable = array();
788 var $mBidtable = array();// array of the translation in each variant
789 var $mUnidtable = array();// array of the translation in each variant
794 * @param string $text the text between -{ and }-
795 * @param object $converter a LanguageConverter object
798 function __construct($text,$converter){
799 $this->mText
= $text;
800 $this->mConverter
=$converter;
801 foreach($converter->mVariants
as $v){
802 $this->mConvTable
[$v]=array();
807 * check if variants array in convert array
809 * @param string $variant Variant language code
810 * @return string Translated text
813 function getTextInBidtable($variants){
814 if(is_string($variants)){ $variants=array($variants); }
815 if(!is_array($variants)) return false;
816 foreach ($variants as $variant){
817 if(array_key_exists($variant, $this->mBidtable
)){
818 return $this->mBidtable
[$variant];
825 * Parse flags with syntax -{FLAG| ... }-
828 function parseFlags(){
829 $text = $this->mText
;
830 if(strlen($text) < 2 ) {
831 $this->mFlags
= array( 'R' );
832 $this->mRules
= $text;
837 $markup = $this->mConverter
->mMarkup
;
838 $validFlags = $this->mConverter
->mFlags
;
840 $tt = explode($markup['flagsep'], $text, 2);
841 if(count($tt) == 2) {
842 $f = explode($markup['varsep'], $tt[0]);
845 if(array_key_exists($ff, $validFlags) &&
846 !in_array($validFlags[$ff], $flags))
847 $flags[] = $validFlags[$ff];
855 if( in_array('R',$flags) ){
856 $flags = array('R');// remove other flags
857 } elseif ( in_array('N',$flags) ){
858 $flags = array('N');// remove other flags
859 } elseif ( in_array('-',$flags) ){
860 $flags = array('-');// remove other flags
861 } elseif (count($flags)==1 && $flags[0]=='T'){
863 } elseif ( in_array('H',$flags) ){
864 // replace A flag, and remove other flags except T
865 $temp=array('+','H');
866 if(in_array('T',$flags)) $temp[] = 'T';
867 if(in_array('D',$flags)) $temp[] = 'D';
870 if ( in_array('A',$flags)) {
874 if ( in_array('D',$flags) )
875 $flags=array_diff($flags,array('S'));
877 if ( count($flags)==0 )
879 $this->mRules
=$rules;
880 $this->mFlags
=$flags;
884 * generate conversion table
887 function parseRules() {
888 $rules = $this->mRules
;
889 $flags = $this->mFlags
;
891 $unidtable = array();
892 $markup = $this->mConverter
->mMarkup
;
894 $choice = explode($markup['varsep'], $rules );
895 foreach($choice as $c) {
896 $v = explode($markup['codesep'], $c);
898 continue;// syntax error, skip
901 $u = explode($markup['unidsep'], $v);
904 } else if(count($u) == 2){
905 $from=trim($u[0]);$v=trim($u[1]);
906 if( array_key_exists($v,$unidtable) && !is_array($unidtable[$v]) )
907 $unidtable[$v]=array($from=>$to);
909 $unidtable[$v][$from]=$to;
911 // syntax error, pass
912 if (!array_key_exists($v,$this->mConverter
->mLanguageNames
)){
914 $unidtable = array();
918 $this->mBidtable
= $bidtable;
919 $this->mUnidtable
= $unidtable;
925 function getRulesDesc(){
926 $codesep = $this->mConverter
->mDescCodeSep
;
927 $varsep = $this->mConverter
->mDescVarSep
;
929 foreach($this->mBidtable
as $k => $v)
930 $text .= $this->mConverter
->mLanguageNames
[$k]."$codesep$v$varsep";
931 foreach($this->mUnidtable
as $k => $a)
932 foreach($a as $from=>$to)
933 $text.="$from⇒".$this->mConverter
->mLanguageNames
[$k]."$codesep$to$varsep";
938 * Parse rules conversion
941 function getRuleConvertedStr($variant,$doConvert){
942 $bidtable = $this->mBidtable
;
943 $unidtable = $this->mUnidtable
;
945 if( count($bidtable) +
count($unidtable) == 0 ){
946 return $this->mRules
;
947 } elseif ($doConvert){// the text converted
948 // display current variant in bidirectional array
949 $disp = $this->getTextInBidtable($variant);
950 // or display current variant in fallbacks
952 $disp = $this->getTextInBidtable(
953 $this->mConverter
->getVariantFallbacks($variant));
954 // or display current variant in unidirectional array
955 if(!$disp && array_key_exists($variant,$unidtable)){
956 $disp = array_values($unidtable[$variant]);
959 // or display frist text under disable manual convert
960 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
961 if(count($bidtable)>0){
962 $disp = array_values($bidtable);
965 $disp = array_values($unidtable);
966 $disp = array_values($disp[0]);
971 } else {// no convert
972 return $this->mRules
;
977 * generate conversion table for all text
980 function generateConvTable(){
981 $flags = $this->mFlags
;
982 $bidtable = $this->mBidtable
;
983 $unidtable = $this->mUnidtable
;
984 $manLevel = $this->mConverter
->mManualLevel
;
987 foreach($this->mConverter
->mVariants
as $v) {
988 /* for bidirectional array
989 fill in the missing variants, if any,
991 if(!array_key_exists($v, $bidtable)) {
992 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
993 $vf = $this->getTextInBidtable($variantFallbacks);
994 if($vf) $bidtable[$v] = $vf;
997 if(array_key_exists($v,$bidtable)){
998 foreach($vmarked as $vo){
999 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1000 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1001 // to introduce a custom mapping between
1002 // words WordZh and WordTw in the whole text
1003 if($manLevel[$v]=='bidirectional'){
1004 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1006 if($manLevel[$vo]=='bidirectional'){
1007 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1012 /*for unidirectional array
1013 fill to convert tables */
1014 $allow_unid = $manLevel[$v]=='bidirectional'
1015 ||
$manLevel[$v]=='unidirectional';
1016 if($allow_unid && array_key_exists($v,$unidtable)){
1017 $ct=$this->mConvTable
[$v];
1018 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1024 * Parse rules and flags
1027 function parse($variant){
1028 if(!$variant) $variant = $this->mConverter
->getPreferredVariant();
1030 $this->parseFlags();
1031 $flags = $this->mFlags
;
1033 if( !in_array('R',$flags) ||
!in_array('N',$flags) ){
1034 //FIXME: may cause trouble here...
1035 //strip since it interferes with the parsing, plus,
1036 //all spaces should be stripped in this tag anyway.
1037 $this->mRules
= str_replace(' ', '', $this->mRules
);
1038 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1039 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1041 $this->parseRules();
1043 $rules = $this->mRules
;
1045 if(count($this->mBidtable
)==0 && count($this->mUnidtable
)==0){
1046 if(in_array('+',$flags) ||
in_array('-',$flags))
1047 // fill all variants if text in -{A/H/-|text} without rules
1048 foreach($this->mConverter
->mVariants
as $v)
1049 $this->mBidtable
[$v] = $rules;
1050 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1051 $this->mFlags
= $flags = array('R');
1054 if( in_array('R',$flags) ) {
1055 // if we don't do content convert, still strip the -{}- tags
1056 $this->mRuleDisplay
= $rules;
1057 } elseif ( in_array('N',$flags) ){
1058 // proces N flag: output current variant name
1059 $this->mRuleDisplay
= $this->mConverter
->mLanguageNames
[trim($rules)];
1060 } elseif ( in_array('D',$flags) ){
1061 // proces D flag: output rules description
1062 $this->mRuleDisplay
= $this->getRulesDesc();
1063 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1064 // proces H,- flag or T only: output nothing
1065 $this->mRuleDisplay
= '';
1066 } elseif ( in_array('S',$flags) ){
1067 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1068 $this->mConverter
->mDoContentConvert
);
1070 $this->mRuleDisplay
= $this->mManualCodeError
;
1073 if ( in_array('T',$flags) ) {
1074 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1075 $this->mConverter
->mDoTitleConvert
);
1078 if (in_array('-', $flags))
1079 $this->mRulesAction
='remove';
1080 if (in_array('+', $flags))
1081 $this->mRulesAction
='add';
1083 $this->generateConvTable();
1089 function hasRules(){
1094 * get display text on markup -{...}-
1097 function getDisplay(){
1098 return $this->mRuleDisplay
;
1101 * get converted title
1104 function getTitle(){
1105 return $this->mRuleTitle
;
1109 * return how deal with conversion rules
1112 function getRulesAction(){
1113 return $this->mRulesAction
;
1117 * get conversion table ( bidirectional and unidirectional conversion table )
1120 function getConvTable(){
1121 return $this->mConvTable
;
1125 * get conversion rules string
1128 function getRules(){
1129 return $this->mRules
;
1133 * get conversion flags
1136 function getFlags(){
1137 return $this->mFlags
;