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
45 * @param array $manualLevel limit for supported variants
48 function __construct($langobj, $maincode,
50 $variantfallbacks=array(),
53 $manualLevel = array() ) {
54 $this->mLangObj
= $langobj;
55 $this->mMainLanguageCode
= $maincode;
56 $this->mVariants
= $variants;
57 $this->mVariantFallbacks
= $variantfallbacks;
58 global $wgLanguageNames;
59 $this->mVariantNames
= $wgLanguageNames;
60 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
64 'unidsep'=>'=>', //for unidirectional conversion
69 $this->mMarkup
= array_merge($m, $markup);
71 // 'S' show converted text
72 // '+' add rules for alltext
73 // 'E' the gave flags is error
74 // these flags above are reserved for program
75 'A'=>'A', // add rule for convert code (all text convert)
76 'T'=>'T', // title convert
77 'R'=>'R', // raw content
78 'D'=>'D', // convert description (subclass implement)
79 '-'=>'-', // remove convert (not implement)
80 'H'=>'H', // add rule for convert code (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 $this->mManualLevel
[$v]=array_key_exists($v,$manualLevel)
93 function getVariants() {
94 return $this->mVariants
;
98 * in case some variant is not defined in the markup, we need
99 * to have some fallback. for example, in zh, normally people
100 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
101 * when zh-sg is preferred but not defined, we will pick zh-hans
102 * in this case. right now this is only used by zh.
104 * @param string $v the language code of the variant
105 * @return string array the code of the fallback language or false if there is no fallback
108 function getVariantFallbacks($v) {
109 if( isset( $this->mVariantFallbacks
[$v] ) ) {
110 return $this->mVariantFallbacks
[$v];
112 return $this->mMainLanguageCode
;
116 * get preferred language variants.
117 * @param boolean $fromUser Get it from $wgUser's preferences
118 * @return string the preferred language code
121 function getPreferredVariant( $fromUser = true ) {
122 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
124 if($this->mPreferredVariant
)
125 return $this->mPreferredVariant
;
127 // figure out user lang without constructing wgLang to avoid infinite recursion
128 $userLang = $wgRequest->getVal( 'uselang', $wgUser->getOption( 'language' ) );
129 // see if interface language is same as content, if not, prevent conversion
130 if( $this->mMainLanguageCode
!= $userLang ){
131 $this->mPreferredVariant
= $this->mMainLanguageCode
; // no conversion
132 return $this->mPreferredVariant
;
135 // see if the preference is set in the request
136 $req = $wgRequest->getText( 'variant' );
137 if( in_array( $req, $this->mVariants
) ) {
138 $this->mPreferredVariant
= $req;
142 // check the syntax /code/ArticleTitle
143 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
144 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
145 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
146 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
147 if(in_array($scriptBase,$this->mVariants
)){
148 $this->mPreferredVariant
= $scriptBase;
149 return $this->mPreferredVariant
;
153 // get language variant preference from logged in users
154 // Don't call this on stub objects because that causes infinite
155 // recursion during initialisation
156 if( $fromUser && $wgUser->isLoggedIn() ) {
157 $this->mPreferredVariant
= $wgUser->getOption('variant');
158 return $this->mPreferredVariant
;
161 // see if default variant is globaly set
162 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
163 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
164 return $this->mPreferredVariant
;
167 # FIXME rewrite code for parsing http header. The current code
168 # is written specific for detecting zh- variants
169 if( !$this->mPreferredVariant
) {
170 // see if some supported language variant is set in the
171 // http header, but we don't set the mPreferredVariant
172 // variable in case this is called before the user's
173 // preference is loaded
174 $pv=$this->mMainLanguageCode
;
175 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
176 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
177 $zh = strstr($header, $pv.'-');
179 $pv = substr($zh,0,5);
182 // don't try to return bad variant
183 if(in_array( $pv, $this->mVariants
))
187 return $this->mMainLanguageCode
;
192 * dictionary-based conversion
194 * @param string $text the text to be converted
195 * @param string $toVariant the target language code
196 * @return string the converted text
199 function autoConvert($text, $toVariant=false) {
200 $fname="LanguageConverter::autoConvert";
202 wfProfileIn( $fname );
204 if(!$this->mTablesLoaded
)
208 $toVariant = $this->getPreferredVariant();
209 if(!in_array($toVariant, $this->mVariants
))
212 /* we convert everything except:
213 1. html markups (anything between < and >)
215 3. place holders created by the parser
218 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
219 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
223 // this one is needed when the text is inside an html markup
224 $htmlfix = '|<[^>]+$|^[^<>]*>';
226 // disable convert to variants between <code></code> tags
227 $codefix = '<code>.+?<\/code>|';
228 // disable convertsion of <script type="text/javascript"> ... </script>
229 $scriptfix = '<script.*?>.*?<\/script>|';
230 // disable conversion of <pre xxxx> ... </pre>
231 $prefix = '<pre.*?>.*?<\/pre>|';
233 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
235 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
237 $m = array_shift($matches);
239 $ret = $this->translate($m[0], $toVariant);
240 $mstart = $m[1]+
strlen($m[0]);
241 foreach($matches as $m) {
242 $ret .= substr($text, $mstart, $m[1]-$mstart);
243 $ret .= $this->translate($m[0], $toVariant);
244 $mstart = $m[1] +
strlen($m[0]);
246 wfProfileOut( $fname );
251 * Translate a string to a variant
252 * Doesn't process markup or do any of that other stuff, for that use convert()
254 * @param string $text Text to convert
255 * @param string $variant Variant language code
256 * @return string Translated text
259 function translate( $text, $variant ) {
260 wfProfileIn( __METHOD__
);
261 if( !$this->mTablesLoaded
)
263 $text = $this->mTables
[$variant]->replace( $text );
264 wfProfileOut( __METHOD__
);
269 * convert text to all supported variants
271 * @param string $text the text to be converted
272 * @return array of string
275 function autoConvertToAllVariants($text) {
276 $fname="LanguageConverter::autoConvertToAllVariants";
277 wfProfileIn( $fname );
278 if( !$this->mTablesLoaded
)
282 foreach($this->mVariants
as $variant) {
283 $ret[$variant] = $this->translate($text, $variant);
286 wfProfileOut( $fname );
291 * convert link text to all supported variants
293 * @param string $text the text to be converted
294 * @return array of string
297 function convertLinkToAllVariants($text) {
298 if( !$this->mTablesLoaded
)
302 $tarray = explode($this->mMarkup
['begin'], $text);
303 $tfirst = array_shift($tarray);
305 foreach($this->mVariants
as $variant)
306 $ret[$variant] = $this->translate($tfirst,$variant);
308 foreach($tarray as $txt) {
309 $marked = explode($this->mMarkup
['end'], $txt, 2);
311 foreach($this->mVariants
as $variant){
312 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
313 if(array_key_exists(1, $marked))
314 $ret[$variant] .= $this->translate($marked[1],$variant);
324 * apply manual conversion
327 function applyManualConv($convRule){
328 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
329 $title = $convRule->getTitle();
331 $this->mTitleFromFlag
= true;
332 $this->mTitleDisplay
= $title;
335 //apply manual conversion table to global table
336 $convTable = $convRule->getConvTable();
337 $action = $convRule->getRulesAction();
338 foreach($convTable as $v=>$t) {
339 if( !in_array($v,$this->mVariants
) )continue;
341 $this->mTables
[$v]->mergeArray($t);
342 elseif ( $action=="remove" )
343 $this->mTables
[$v]->removeArray($t);
348 * Convert text using a parser object for context
351 function parserConvert( $text, &$parser ) {
352 global $wgDisableLangConversion;
353 /* don't do anything if this is the conversion table */
354 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
355 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
360 if($wgDisableLangConversion)
363 $text = $this->convert( $text );
364 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
372 function convertTitle($text){
373 // check for __NOTC__ tag
374 if( !$this->mDoTitleConvert
) {
375 $this->mTitleDisplay
= $text;
379 // use the title from the T flag if any
380 if($this->mTitleFromFlag
){
381 $this->mTitleFromFlag
= false;
382 return $this->mTitleDisplay
;
386 $isredir = $wgRequest->getText( 'redirect', 'yes' );
387 $action = $wgRequest->getText( 'action' );
388 if ( $isredir == 'no' ||
$action == 'edit' ) {
391 $this->mTitleDisplay
= $this->convert($text);
392 return $this->mTitleDisplay
;
397 * convert text to different variants of a language. the automatic
398 * conversion is done in autoConvert(). here we parse the text
399 * marked with -{}-, which specifies special conversions of the
400 * text that can not be accomplished in autoConvert()
402 * syntax of the markup:
403 * -{code1:text1;code2:text2;...}- or
404 * -{flags|code1:text1;code2:text2;...}- or
405 * -{text}- in which case no conversion should take place for text
407 * @param string $text text to be converted
408 * @param bool $isTitle whether this conversion is for the article title
409 * @return string converted text
412 function convert( $text , $isTitle=false) {
414 $mw =& MagicWord
::get( 'notitleconvert' );
415 if( $mw->matchAndRemove( $text ) )
416 $this->mDoTitleConvert
= false;
417 $mw =& MagicWord
::get( 'nocontentconvert' );
418 if( $mw->matchAndRemove( $text ) ) {
419 $this->mDoContentConvert
= false;
422 // no conversion if redirecting
423 $mw =& MagicWord
::get( 'redirect' );
424 if( $mw->matchStart( $text ))
427 // for title convertion
428 if ($isTitle) return $this->convertTitle($text);
430 $plang = $this->getPreferredVariant();
431 $tarray = explode($this->mMarkup
['end'], $text);
433 foreach($tarray as $txt) {
434 $marked = explode($this->mMarkup
['begin'], $txt, 2);
436 if( $this->mDoContentConvert
)
437 $text .= $this->autoConvert($marked[0],$plang);
441 if(array_key_exists(1, $marked)){
442 // strip the flags from syntax like -{T| ... }-
443 $crule = new ConverterRule($marked[1], $this);
444 $crule->parse($plang);
446 $text .= $crule->getDisplay();
447 $this->applyManualConv($crule);
455 * if a language supports multiple variants, it is
456 * possible that non-existing link in one variant
457 * actually exists in another variant. this function
458 * tries to find it. See e.g. LanguageZh.php
460 * @param string $link the name of the link
461 * @param mixed $nt the title object of the link
462 * @return null the input parameters may be modified upon return
465 function findVariantLink( &$link, &$nt ) {
466 global $wgDisableLangConversion;
467 $linkBatch = new LinkBatch();
472 $ns = $nt->getNamespace();
474 $variants = $this->autoConvertToAllVariants($link);
475 if($variants == false) //give up
480 foreach( $variants as $v ) {
482 $varnt = Title
::newFromText( $v, $ns );
483 if(!is_null($varnt)){
484 $linkBatch->addObj($varnt);
490 // fetch all variants in single query
491 $linkBatch->execute();
493 foreach( $titles as $varnt ) {
494 if( $varnt->getArticleID() > 0 ) {
496 if( !$wgDisableLangConversion )
504 * returns language specific hash options
508 function getExtraHashOptions() {
509 $variant = $this->getPreferredVariant();
510 return '!' . $variant ;
514 * get title text as defined in the body of the article text
518 function getParsedTitle() {
519 return $this->mTitleDisplay
;
523 * a write lock to the cache
527 function lockCache() {
530 for($i=0; $i<30; $i++
) {
531 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
543 function unlockCache() {
545 $wgMemc->delete($this->mCacheKey
. "lock");
550 * Load default conversion tables
551 * This method must be implemented in derived class
555 function loadDefaultTables() {
556 $name = get_class($this);
557 wfDie("Must implement loadDefaultTables() method in class $name");
561 * load conversion tables either from the cache or the disk
564 function loadTables($fromcache=true) {
566 if( $this->mTablesLoaded
)
568 wfProfileIn( __METHOD__
);
569 $this->mTablesLoaded
= true;
570 $this->mTables
= false;
572 wfProfileIn( __METHOD__
.'-cache' );
573 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
574 wfProfileOut( __METHOD__
.'-cache' );
576 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
577 wfProfileIn( __METHOD__
.'-recache' );
578 // not in cache, or we need a fresh reload.
579 // we will first load the default tables
580 // then update them using things in MediaWiki:Zhconversiontable/*
581 $this->loadDefaultTables();
582 foreach($this->mVariants
as $var) {
583 $cached = $this->parseCachedTable($var);
584 $this->mTables
[$var]->mergeArray($cached);
587 $this->postLoadTables();
588 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
590 if($this->lockCache()) {
591 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
592 $this->unlockCache();
594 wfProfileOut( __METHOD__
.'-recache' );
596 wfProfileOut( __METHOD__
);
600 * Hook for post processig after conversion tables are loaded
603 function postLoadTables() {}
606 * Reload the conversion tables
610 function reloadTables() {
612 unset($this->mTables
);
613 $this->mTablesLoaded
= false;
614 $this->loadTables(false);
619 * parse the conversion table stored in the cache
621 * the tables should be in blocks of the following form:
628 * to make the tables more manageable, subpages are allowed
629 * and will be parsed recursively if $recursive=true
632 function parseCachedTable($code, $subpage='', $recursive=true) {
633 global $wgMessageCache;
634 static $parsed = array();
636 if(!is_object($wgMessageCache))
639 $key = 'Conversiontable/'.$code;
641 $key .= '/' . $subpage;
643 if(array_key_exists($key, $parsed))
646 if ( strpos( $code, '/' ) === false ) {
647 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
649 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
650 if ( $title && $title->exists() ) {
651 $article = new Article( $title );
652 $txt = $article->getContents();
658 // get all subpage links of the form
659 // [[MediaWiki:conversiontable/zh-xx/...|...]]
660 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
661 $subs = explode('[[', $txt);
663 foreach( $subs as $sub ) {
664 $link = explode(']]', $sub, 2);
665 if(count($link) != 2)
667 $b = explode('|', $link[0]);
668 $b = explode('/', trim($b[0]), 3);
674 if($b[0] == $linkhead && $b[1] == $code) {
675 $sublinks[] = $sublink;
680 // parse the mappings in this page
681 $blocks = explode($this->mMarkup
['begin'], $txt);
682 array_shift($blocks);
684 foreach($blocks as $block) {
685 $mappings = explode($this->mMarkup
['end'], $block, 2);
686 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
687 $table = explode( ';', $stripped );
688 foreach( $table as $t ) {
689 $m = explode( '=>', $t );
690 if( count( $m ) != 2)
692 // trim any trailling comments starting with '//'
693 $tt = explode('//', $m[1], 2);
694 $ret[trim($m[0])] = trim($tt[0]);
697 $parsed[$key] = true;
700 // recursively parse the subpages
702 foreach($sublinks as $link) {
703 $s = $this->parseCachedTable($code, $link, $recursive);
704 $ret = array_merge($ret, $s);
708 if ($this->mUcfirst
) {
709 foreach ($ret as $k => $v) {
710 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
717 * Enclose a string with the "no conversion" tag. This is used by
718 * various functions in the Parser
720 * @param string $text text to be tagged for no conversion
721 * @return string the tagged text
724 function markNoConversion($text, $noParse=false) {
725 # don't mark if already marked
726 if(strpos($text, $this->mMarkup
['begin']) ||
727 strpos($text, $this->mMarkup
['end']))
730 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
735 * convert the sorting key for category links. this should make different
736 * keys that are variants of each other map to the same key
738 function convertCategoryKey( $key ) {
742 * hook to refresh the cache of conversion tables when
743 * MediaWiki:conversiontable* is updated
746 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
747 $titleobj = $article->getTitle();
748 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
749 $title = $titleobj->getDBkey();
750 $t = explode('/', $title, 3);
752 if( $c > 1 && $t[0] == 'Conversiontable' ) {
753 if(in_array($t[1], $this->mVariants
)) {
754 $this->reloadTables();
762 * Armour rendered math against conversion
763 * Wrap math into rawoutput -{R| math }- syntax
766 function armourMath($text){
767 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
773 * parser for rules of language conversion , parse rules in -{ }- tag
775 * @author fdcn <fdcn64@gmail.com>
777 class ConverterRule
{
778 var $mText; // original text in -{text}-
779 var $mConverter; // LanguageConverter object
780 var $mManualCodeError='<strong class="error">code error!</strong>';
781 var $mRuleDisplay = '',$mRuleTitle=false;
782 var $mRules = '';// string : the text of the rules
783 var $mRulesAction = 'none';
784 var $mFlags = array();
785 var $mConvTable = array();
786 var $mBidtable = array();// array of the translation in each variant
787 var $mUnidtable = array();// array of the translation in each variant
792 * @param string $text the text between -{ and }-
793 * @param object $converter a LanguageConverter object
796 function __construct($text,$converter){
797 $this->mText
= $text;
798 $this->mConverter
=$converter;
799 foreach($converter->mVariants
as $v){
800 $this->mConvTable
[$v]=array();
805 * check if variants array in convert array
807 * @param string $variant Variant language code
808 * @return string Translated text
811 function getTextInBidtable($variants){
812 if(is_string($variants)){ $variants=array($variants); }
813 if(!is_array($variants)) return false;
814 foreach ($variants as $variant){
815 if(array_key_exists($variant, $this->mBidtable
)){
816 return $this->mBidtable
[$variant];
823 * Parse flags with syntax -{FLAG| ... }-
826 function parseFlags(){
827 $text = $this->mText
;
828 if(strlen($text) < 2 ) {
829 $this->mFlags
= array( 'R' );
830 $this->mRules
= $text;
835 $markup = $this->mConverter
->mMarkup
;
836 $validFlags = $this->mConverter
->mFlags
;
838 $tt = explode($markup['flagsep'], $text, 2);
839 if(count($tt) == 2) {
840 $f = explode($markup['varsep'], $tt[0]);
843 if(array_key_exists($ff, $validFlags) &&
844 !in_array($validFlags[$ff], $flags))
845 $flags[] = $validFlags[$ff];
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 $flags = $this->mFlags
;
980 $bidtable = $this->mBidtable
;
981 $unidtable = $this->mUnidtable
;
982 $manLevel = $this->mConverter
->mManualLevel
;
985 foreach($this->mConverter
->mVariants
as $v) {
986 /* for bidirectional array
987 fill in the missing variants, if any,
989 if(!array_key_exists($v, $bidtable)) {
990 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
991 $vf = $this->getTextInBidtable($variantFallbacks);
992 if($vf) $bidtable[$v] = $vf;
995 if(array_key_exists($v,$bidtable)){
996 foreach($vmarked as $vo){
997 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
998 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
999 // to introduce a custom mapping between
1000 // words WordZh and WordTw in the whole text
1001 if($manLevel[$v]=='bidirectional'){
1002 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1004 if($manLevel[$vo]=='bidirectional'){
1005 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1010 /*for unidirectional array
1011 fill to convert tables */
1012 $allow_unid = $manLevel[$v]=='bidirectional'
1013 ||
$manLevel[$v]=='unidirectional';
1014 if($allow_unid && array_key_exists($v,$unidtable)){
1015 $ct=$this->mConvTable
[$v];
1016 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1022 * Parse rules and flags
1025 function parse($variant){
1026 if(!$variant) $variant = $this->mConverter
->getPreferredVariant();
1028 $this->parseFlags();
1029 $flags = $this->mFlags
;
1031 if( !in_array('R',$flags) ||
!in_array('N',$flags) ){
1032 //FIXME: may cause trouble here...
1033 //strip since it interferes with the parsing, plus,
1034 //all spaces should be stripped in this tag anyway.
1035 $this->mRules
= str_replace(' ', '', $this->mRules
);
1036 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1037 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1039 $this->parseRules();
1041 $rules = $this->mRules
;
1043 if(count($this->mBidtable
)==0 && count($this->mUnidtable
)==0){
1044 if(in_array('+',$flags) ||
in_array('-',$flags))
1045 // fill all variants if text in -{A/H/-|text} without rules
1046 foreach($this->mConverter
->mVariants
as $v)
1047 $this->mBidtable
[$v] = $rules;
1048 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1049 $this->mFlags
= $flags = array('R');
1052 if( in_array('R',$flags) ) {
1053 // if we don't do content convert, still strip the -{}- tags
1054 $this->mRuleDisplay
= $rules;
1055 } elseif ( in_array('N',$flags) ){
1056 // proces N flag: output current variant name
1057 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1058 } elseif ( in_array('D',$flags) ){
1059 // proces D flag: output rules description
1060 $this->mRuleDisplay
= $this->getRulesDesc();
1061 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1062 // proces H,- flag or T only: output nothing
1063 $this->mRuleDisplay
= '';
1064 } elseif ( in_array('S',$flags) ){
1065 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1066 $this->mConverter
->mDoContentConvert
);
1068 $this->mRuleDisplay
= $this->mManualCodeError
;
1071 if ( in_array('T',$flags) ) {
1072 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1073 $this->mConverter
->mDoTitleConvert
);
1076 if (in_array('-', $flags))
1077 $this->mRulesAction
='remove';
1078 if (in_array('+', $flags))
1079 $this->mRulesAction
='add';
1081 $this->generateConvTable();
1087 function hasRules(){
1092 * get display text on markup -{...}-
1095 function getDisplay(){
1096 return $this->mRuleDisplay
;
1099 * get converted title
1102 function getTitle(){
1103 return $this->mRuleTitle
;
1107 * return how deal with conversion rules
1110 function getRulesAction(){
1111 return $this->mRulesAction
;
1115 * get conversion table ( bidirectional and unidirectional conversion table )
1118 function getConvTable(){
1119 return $this->mConvTable
;
1123 * get conversion rules string
1126 function getRules(){
1127 return $this->mRules
;
1131 * get conversion flags
1134 function getFlags(){
1135 return $this->mFlags
;