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 // more efficient than array_merge(), about 2.5 times.
300 $this->mManualAddTables
[$v][$from] = $to;
303 elseif ( $action=="remove" )
304 $this->mManualRemoveTables
[$v] = array_merge($this->mManualRemoveTables
[$v], $t);
309 * apply manual conversion from $this->mManualAddTables and $this->mManualRemoveTables
312 function applyManualConv(){
313 //apply manual conversion table to global table
314 foreach($this->mVariants
as $v) {
315 if (count($this->mManualAddTables
[$v]) > 0) {
316 $this->mTables
[$v]->mergeArray($this->mManualAddTables
[$v]);
318 if (count($this->mManualRemoveTables
[$v]) > 0)
319 $this->mTables
[$v]->removeArray($this->mManualRemoveTables
[$v]);
324 * Convert text using a parser object for context
327 function parserConvert( $text, &$parser ) {
328 global $wgDisableLangConversion;
329 /* don't do anything if this is the conversion table */
330 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
331 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
336 if($wgDisableLangConversion)
339 $text = $this->convert( $text );
340 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
348 function convertTitle($text){
349 global $wgDisableTitleConversion, $wgUser;
351 // check for global param and __NOTC__ tag
352 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
$wgUser->getOption('noconvertlink') == 1 ) {
353 $this->mTitleDisplay
= $text;
357 // use the title from the T flag if any
358 if($this->mTitleFromFlag
){
359 $this->mTitleFromFlag
= false;
360 return $this->mTitleDisplay
;
364 $isredir = $wgRequest->getText( 'redirect', 'yes' );
365 $action = $wgRequest->getText( 'action' );
366 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
367 if ( $isredir == 'no' ||
$action == 'edit' ||
$action == 'submit' ||
$linkconvert == 'no' ) {
370 $this->mTitleDisplay
= $this->convert($text);
371 return $this->mTitleDisplay
;
376 * convert text to different variants of a language. the automatic
377 * conversion is done in autoConvert(). here we parse the text
378 * marked with -{}-, which specifies special conversions of the
379 * text that can not be accomplished in autoConvert()
381 * syntax of the markup:
382 * -{code1:text1;code2:text2;...}- or
383 * -{flags|code1:text1;code2:text2;...}- or
384 * -{text}- in which case no conversion should take place for text
386 * @param string $text text to be converted
387 * @param bool $isTitle whether this conversion is for the article title
388 * @return string converted text
391 function convert( $text , $isTitle=false) {
393 $mw =& MagicWord
::get( 'notitleconvert' );
394 if( $mw->matchAndRemove( $text ) )
395 $this->mDoTitleConvert
= false;
396 $mw =& MagicWord
::get( 'nocontentconvert' );
397 if( $mw->matchAndRemove( $text ) ) {
398 $this->mDoContentConvert
= false;
401 // no conversion if redirecting
402 $mw =& MagicWord
::get( 'redirect' );
403 if( $mw->matchStart( $text ))
406 // for title convertion
407 if ($isTitle) return $this->convertTitle($text);
409 $plang = $this->getPreferredVariant();
410 $tarray = StringUtils
::explode($this->mMarkup
['end'], $text);
414 foreach($tarray as $txt) {
415 $marked = explode($this->mMarkup
['begin'], $txt, 2);
416 if (array_key_exists(1, $marked)) {
417 $crule = new ConverterRule($marked[1], $this);
418 $crule->parse($plang);
419 $marked[1] = $crule->getDisplay();
420 $this->prepareManualConv($crule);
423 $marked[0] .= $this->mMarkup
['end'];
424 array_push($marks, $marked);
426 $this->applyManualConv();
427 foreach ($marks as $marked) {
428 if( $this->mDoContentConvert
)
429 $text .= $this->autoConvert($marked[0],$plang);
432 if( array_key_exists(1, $marked) )
435 // Remove the last delimiter (wasn't real)
436 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
442 * if a language supports multiple variants, it is
443 * possible that non-existing link in one variant
444 * actually exists in another variant. this function
445 * tries to find it. See e.g. LanguageZh.php
447 * @param string $link the name of the link
448 * @param mixed $nt the title object of the link
449 * @return null the input parameters may be modified upon return
452 function findVariantLink( &$link, &$nt, $forTemplate = false ) {
453 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
454 $isredir = $wgRequest->getText( 'redirect', 'yes' );
455 $action = $wgRequest->getText( 'action' );
456 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
457 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
458 $linkBatch = new LinkBatch();
462 if ( $disableLinkConversion ||
( !$forTemplate && ( $isredir == 'no' ||
$action == 'edit'
463 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) ) {
468 $ns = $nt->getNamespace();
470 $variants = $this->autoConvertToAllVariants($link);
471 if($variants == false) //give up
476 foreach( $variants as $v ) {
478 $varnt = Title
::newFromText( $v, $ns );
479 if(!is_null($varnt)){
480 $linkBatch->addObj($varnt);
486 // fetch all variants in single query
487 $linkBatch->execute();
489 foreach( $titles as $varnt ) {
490 if( $varnt->getArticleID() > 0 ) {
499 * returns language specific hash options
503 function getExtraHashOptions() {
504 $variant = $this->getPreferredVariant();
505 return '!' . $variant ;
509 * get title text as defined in the body of the article text
513 function getParsedTitle() {
514 return $this->mTitleDisplay
;
518 * a write lock to the cache
522 function lockCache() {
525 for($i=0; $i<30; $i++
) {
526 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
538 function unlockCache() {
540 $wgMemc->delete($this->mCacheKey
. "lock");
545 * Load default conversion tables
546 * This method must be implemented in derived class
550 function loadDefaultTables() {
551 $name = get_class($this);
552 wfDie("Must implement loadDefaultTables() method in class $name");
556 * load conversion tables either from the cache or the disk
559 function loadTables($fromcache=true) {
561 if( $this->mTablesLoaded
)
563 wfProfileIn( __METHOD__
);
564 $this->mTablesLoaded
= true;
565 $this->mTables
= false;
567 wfProfileIn( __METHOD__
.'-cache' );
568 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
569 wfProfileOut( __METHOD__
.'-cache' );
571 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
572 wfProfileIn( __METHOD__
.'-recache' );
573 // not in cache, or we need a fresh reload.
574 // we will first load the default tables
575 // then update them using things in MediaWiki:Zhconversiontable/*
576 $this->loadDefaultTables();
577 foreach($this->mVariants
as $var) {
578 $cached = $this->parseCachedTable($var);
579 $this->mTables
[$var]->mergeArray($cached);
582 $this->postLoadTables();
583 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
585 if($this->lockCache()) {
586 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
587 $this->unlockCache();
589 wfProfileOut( __METHOD__
.'-recache' );
591 wfProfileOut( __METHOD__
);
595 * Hook for post processig after conversion tables are loaded
598 function postLoadTables() {}
601 * Reload the conversion tables
605 function reloadTables() {
607 unset($this->mTables
);
608 $this->mTablesLoaded
= false;
609 $this->loadTables(false);
614 * parse the conversion table stored in the cache
616 * the tables should be in blocks of the following form:
623 * to make the tables more manageable, subpages are allowed
624 * and will be parsed recursively if $recursive=true
627 function parseCachedTable($code, $subpage='', $recursive=true) {
628 global $wgMessageCache;
629 static $parsed = array();
631 if(!is_object($wgMessageCache))
634 $key = 'Conversiontable/'.$code;
636 $key .= '/' . $subpage;
638 if(array_key_exists($key, $parsed))
641 if ( strpos( $code, '/' ) === false ) {
642 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
644 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
645 if ( $title && $title->exists() ) {
646 $article = new Article( $title );
647 $txt = $article->getContents();
653 // get all subpage links of the form
654 // [[MediaWiki:conversiontable/zh-xx/...|...]]
655 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
656 $subs = explode('[[', $txt);
658 foreach( $subs as $sub ) {
659 $link = explode(']]', $sub, 2);
660 if(count($link) != 2)
662 $b = explode('|', $link[0]);
663 $b = explode('/', trim($b[0]), 3);
669 if($b[0] == $linkhead && $b[1] == $code) {
670 $sublinks[] = $sublink;
675 // parse the mappings in this page
676 $blocks = explode($this->mMarkup
['begin'], $txt);
677 array_shift($blocks);
679 foreach($blocks as $block) {
680 $mappings = explode($this->mMarkup
['end'], $block, 2);
681 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
682 $table = explode( ';', $stripped );
683 foreach( $table as $t ) {
684 $m = explode( '=>', $t );
685 if( count( $m ) != 2)
687 // trim any trailling comments starting with '//'
688 $tt = explode('//', $m[1], 2);
689 $ret[trim($m[0])] = trim($tt[0]);
692 $parsed[$key] = true;
695 // recursively parse the subpages
697 foreach($sublinks as $link) {
698 $s = $this->parseCachedTable($code, $link, $recursive);
699 $ret = array_merge($ret, $s);
703 if ($this->mUcfirst
) {
704 foreach ($ret as $k => $v) {
705 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
712 * Enclose a string with the "no conversion" tag. This is used by
713 * various functions in the Parser
715 * @param string $text text to be tagged for no conversion
716 * @return string the tagged text
719 function markNoConversion($text, $noParse=false) {
720 # don't mark if already marked
721 if(strpos($text, $this->mMarkup
['begin']) ||
722 strpos($text, $this->mMarkup
['end']))
725 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
730 * convert the sorting key for category links. this should make different
731 * keys that are variants of each other map to the same key
733 function convertCategoryKey( $key ) {
737 * hook to refresh the cache of conversion tables when
738 * MediaWiki:conversiontable* is updated
741 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
742 $titleobj = $article->getTitle();
743 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
744 $title = $titleobj->getDBkey();
745 $t = explode('/', $title, 3);
747 if( $c > 1 && $t[0] == 'Conversiontable' ) {
748 if(in_array($t[1], $this->mVariants
)) {
749 $this->reloadTables();
757 * Armour rendered math against conversion
758 * Wrap math into rawoutput -{R| math }- syntax
761 function armourMath($text){
762 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
768 * parser for rules of language conversion , parse rules in -{ }- tag
770 * @author fdcn <fdcn64@gmail.com>
772 class ConverterRule
{
773 var $mText; // original text in -{text}-
774 var $mConverter; // LanguageConverter object
775 var $mManualCodeError='<strong class="error">code error!</strong>';
776 var $mRuleDisplay = '',$mRuleTitle=false;
777 var $mRules = '';// string : the text of the rules
778 var $mRulesAction = 'none';
779 var $mFlags = array();
780 var $mConvTable = array();
781 var $mBidtable = array();// array of the translation in each variant
782 var $mUnidtable = array();// array of the translation in each variant
787 * @param string $text the text between -{ and }-
788 * @param object $converter a LanguageConverter object
791 function __construct($text,$converter){
792 $this->mText
= $text;
793 $this->mConverter
=$converter;
794 foreach($converter->mVariants
as $v){
795 $this->mConvTable
[$v]=array();
800 * check if variants array in convert array
802 * @param string $variant Variant language code
803 * @return string Translated text
806 function getTextInBidtable($variants){
807 if(is_string($variants)){ $variants=array($variants); }
808 if(!is_array($variants)) return false;
809 foreach ($variants as $variant){
810 if(array_key_exists($variant, $this->mBidtable
)){
811 return $this->mBidtable
[$variant];
818 * Parse flags with syntax -{FLAG| ... }-
821 function parseFlags(){
822 $text = $this->mText
;
823 if(strlen($text) < 2 ) {
824 $this->mFlags
= array( 'R' );
825 $this->mRules
= $text;
830 $markup = $this->mConverter
->mMarkup
;
831 $validFlags = $this->mConverter
->mFlags
;
833 $tt = explode($markup['flagsep'], $text, 2);
834 if(count($tt) == 2) {
835 $f = explode($markup['varsep'], $tt[0]);
838 if(array_key_exists($ff, $validFlags) &&
839 !in_array($validFlags[$ff], $flags))
840 $flags[] = $validFlags[$ff];
848 if( in_array('R',$flags) ){
849 $flags = array('R');// remove other flags
850 } elseif ( in_array('N',$flags) ){
851 $flags = array('N');// remove other flags
852 } elseif ( in_array('-',$flags) ){
853 $flags = array('-');// remove other flags
854 } elseif (count($flags)==1 && $flags[0]=='T'){
856 } elseif ( in_array('H',$flags) ){
857 // replace A flag, and remove other flags except T
858 $temp=array('+','H');
859 if(in_array('T',$flags)) $temp[] = 'T';
860 if(in_array('D',$flags)) $temp[] = 'D';
863 if ( in_array('A',$flags)) {
867 if ( in_array('D',$flags) )
868 $flags=array_diff($flags,array('S'));
870 if ( count($flags)==0 )
872 $this->mRules
=$rules;
873 $this->mFlags
=$flags;
877 * generate conversion table
880 function parseRules() {
881 $rules = $this->mRules
;
882 $flags = $this->mFlags
;
884 $unidtable = array();
885 $markup = $this->mConverter
->mMarkup
;
887 $choice = explode($markup['varsep'], $rules );
888 foreach($choice as $c) {
889 $v = explode($markup['codesep'], $c);
891 continue;// syntax error, skip
894 $u = explode($markup['unidsep'], $v);
897 } else if(count($u) == 2){
898 $from=trim($u[0]);$v=trim($u[1]);
899 if( array_key_exists($v,$unidtable) && !is_array($unidtable[$v]) )
900 $unidtable[$v]=array($from=>$to);
902 $unidtable[$v][$from]=$to;
904 // syntax error, pass
905 if (!array_key_exists($v,$this->mConverter
->mLanguageNames
)){
907 $unidtable = array();
911 $this->mBidtable
= $bidtable;
912 $this->mUnidtable
= $unidtable;
918 function getRulesDesc(){
919 $codesep = $this->mConverter
->mDescCodeSep
;
920 $varsep = $this->mConverter
->mDescVarSep
;
922 foreach($this->mBidtable
as $k => $v)
923 $text .= $this->mConverter
->mLanguageNames
[$k]."$codesep$v$varsep";
924 foreach($this->mUnidtable
as $k => $a)
925 foreach($a as $from=>$to)
926 $text.="$from⇒".$this->mConverter
->mLanguageNames
[$k]."$codesep$to$varsep";
931 * Parse rules conversion
934 function getRuleConvertedStr($variant,$doConvert){
935 $bidtable = $this->mBidtable
;
936 $unidtable = $this->mUnidtable
;
938 if( count($bidtable) +
count($unidtable) == 0 ){
939 return $this->mRules
;
940 } elseif ($doConvert){// the text converted
941 // display current variant in bidirectional array
942 $disp = $this->getTextInBidtable($variant);
943 // or display current variant in fallbacks
945 $disp = $this->getTextInBidtable(
946 $this->mConverter
->getVariantFallbacks($variant));
947 // or display current variant in unidirectional array
948 if(!$disp && array_key_exists($variant,$unidtable)){
949 $disp = array_values($unidtable[$variant]);
952 // or display frist text under disable manual convert
953 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
954 if(count($bidtable)>0){
955 $disp = array_values($bidtable);
958 $disp = array_values($unidtable);
959 $disp = array_values($disp[0]);
964 } else {// no convert
965 return $this->mRules
;
970 * generate conversion table for all text
973 function generateConvTable(){
974 $flags = $this->mFlags
;
975 $bidtable = $this->mBidtable
;
976 $unidtable = $this->mUnidtable
;
977 $manLevel = $this->mConverter
->mManualLevel
;
980 foreach($this->mConverter
->mVariants
as $v) {
981 /* for bidirectional array
982 fill in the missing variants, if any,
984 if(!array_key_exists($v, $bidtable)) {
985 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
986 $vf = $this->getTextInBidtable($variantFallbacks);
987 if($vf) $bidtable[$v] = $vf;
990 if(array_key_exists($v,$bidtable)){
991 foreach($vmarked as $vo){
992 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
993 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
994 // to introduce a custom mapping between
995 // words WordZh and WordTw in the whole text
996 if($manLevel[$v]=='bidirectional'){
997 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
999 if($manLevel[$vo]=='bidirectional'){
1000 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1005 /*for unidirectional array
1006 fill to convert tables */
1007 $allow_unid = $manLevel[$v]=='bidirectional'
1008 ||
$manLevel[$v]=='unidirectional';
1009 if($allow_unid && array_key_exists($v,$unidtable)){
1010 $ct=$this->mConvTable
[$v];
1011 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1017 * Parse rules and flags
1020 function parse($variant){
1021 if(!$variant) $variant = $this->mConverter
->getPreferredVariant();
1023 $this->parseFlags();
1024 $flags = $this->mFlags
;
1026 if( !in_array('R',$flags) ||
!in_array('N',$flags) ){
1027 //FIXME: may cause trouble here...
1028 //strip since it interferes with the parsing, plus,
1029 //all spaces should be stripped in this tag anyway.
1030 $this->mRules
= str_replace(' ', '', $this->mRules
);
1031 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1032 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1034 $this->parseRules();
1036 $rules = $this->mRules
;
1038 if(count($this->mBidtable
)==0 && count($this->mUnidtable
)==0){
1039 if(in_array('+',$flags) ||
in_array('-',$flags))
1040 // fill all variants if text in -{A/H/-|text} without rules
1041 foreach($this->mConverter
->mVariants
as $v)
1042 $this->mBidtable
[$v] = $rules;
1043 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1044 $this->mFlags
= $flags = array('R');
1047 if( in_array('R',$flags) ) {
1048 // if we don't do content convert, still strip the -{}- tags
1049 $this->mRuleDisplay
= $rules;
1050 } elseif ( in_array('N',$flags) ){
1051 // proces N flag: output current variant name
1052 $this->mRuleDisplay
= $this->mConverter
->mLanguageNames
[trim($rules)];
1053 } elseif ( in_array('D',$flags) ){
1054 // proces D flag: output rules description
1055 $this->mRuleDisplay
= $this->getRulesDesc();
1056 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1057 // proces H,- flag or T only: output nothing
1058 $this->mRuleDisplay
= '';
1059 } elseif ( in_array('S',$flags) ){
1060 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1061 $this->mConverter
->mDoContentConvert
);
1063 $this->mRuleDisplay
= $this->mManualCodeError
;
1066 if ( in_array('T',$flags) ) {
1067 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1068 $this->mConverter
->mDoTitleConvert
);
1071 if (in_array('-', $flags))
1072 $this->mRulesAction
='remove';
1073 if (in_array('+', $flags))
1074 $this->mRulesAction
='add';
1076 $this->generateConvTable();
1082 function hasRules(){
1087 * get display text on markup -{...}-
1090 function getDisplay(){
1091 return $this->mRuleDisplay
;
1094 * get converted title
1097 function getTitle(){
1098 return $this->mRuleTitle
;
1102 * return how deal with conversion rules
1105 function getRulesAction(){
1106 return $this->mRulesAction
;
1110 * get conversion table ( bidirectional and unidirectional conversion table )
1113 function getConvTable(){
1114 return $this->mConvTable
;
1118 * get conversion rules string
1121 function getRules(){
1122 return $this->mRules
;
1126 * get conversion flags
1129 function getFlags(){
1130 return $this->mFlags
;