6 * @author Zhengzhu Feng <zhengzhu@gmail.com>
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
8 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>
11 class LanguageConverter
{
12 var $mPreferredVariant='';
13 var $mMainLanguageCode;
14 var $mVariants, $mVariantFallbacks, $mVariantNames;
15 var $mTablesLoaded = false;
17 var $mTitleDisplay='';
18 var $mDoTitleConvert=true, $mDoContentConvert=true;
19 var $mManualLevel; // 'bidirectional' 'unidirectional' 'disable' for each variants
20 var $mTitleFromFlag = false;
25 var $mUcfirst = false;
27 const CACHE_VERSION_KEY
= 'VERSION 6';
32 * @param string $maincode the main language code of this language
33 * @param array $variants the supported variants of this language
34 * @param array $variantfallback the fallback language of each variant
35 * @param array $markup array defining the markup used for manual conversion
36 * @param array $flags array defining the custom strings that maps to the flags
39 function __construct($langobj, $maincode,
41 $variantfallbacks=array(),
44 $manualLevel = array() ) {
45 $this->mLangObj
= $langobj;
46 $this->mMainLanguageCode
= $maincode;
47 $this->mVariants
= $variants;
48 $this->mVariantFallbacks
= $variantfallbacks;
49 global $wgLanguageNames;
50 $this->mVariantNames
= $wgLanguageNames;
51 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
55 'unidsep'=>'=>', //for unidirectional conversion
60 $this->mMarkup
= array_merge($m, $markup);
62 // 'S' show converted text
63 // '+' add rules for alltext
64 // 'E' the gave flags is error
65 // these flags above are reserved for program
66 'A'=>'A', // add rule for convert code (all text convert)
67 'T'=>'T', // title convert
68 'R'=>'R', // raw content
69 'D'=>'D', // convert description (subclass implement)
70 '-'=>'-', // remove convert (not implement)
71 'H'=>'H', // add rule for convert code (but no display in placed code )
72 'N'=>'N' // current variant name
74 $this->mFlags
= array_merge($f, $flags);
75 foreach( $this->mVariants
as $v)
76 $this->mManualLevel
[$v]=array_key_exists($v,$manualLevel)
84 function getVariants() {
85 return $this->mVariants
;
89 * in case some variant is not defined in the markup, we need
90 * to have some fallback. for example, in zh, normally people
91 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
92 * when zh-sg is preferred but not defined, we will pick zh-hans
93 * in this case. right now this is only used by zh.
95 * @param string $v the language code of the variant
96 * @return string array the code of the fallback language or false if there is no fallback
99 function getVariantFallbacks($v) {
100 if( isset( $this->mVariantFallbacks
[$v] ) ) {
101 return $this->mVariantFallbacks
[$v];
103 return $this->mMainLanguageCode
;
107 * get preferred language variants.
108 * @param boolean $fromUser Get it from $wgUser's preferences
109 * @return string the preferred language code
112 function getPreferredVariant( $fromUser = true ) {
113 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
115 if($this->mPreferredVariant
)
116 return $this->mPreferredVariant
;
118 // see if the preference is set in the request
119 $req = $wgRequest->getText( 'variant' );
120 if( in_array( $req, $this->mVariants
) ) {
121 $this->mPreferredVariant
= $req;
125 // check the syntax /code/ArticleTitle
126 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
127 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
128 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
129 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
130 if(in_array($scriptBase,$this->mVariants
)){
131 $this->mPreferredVariant
= $scriptBase;
132 return $this->mPreferredVariant
;
136 // get language variant preference from logged in users
137 // Don't call this on stub objects because that causes infinite
138 // recursion during initialisation
139 if( $fromUser && $wgUser->isLoggedIn() ) {
140 $this->mPreferredVariant
= $wgUser->getOption('variant');
141 return $this->mPreferredVariant
;
144 // see if default variant is globaly set
145 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
146 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
147 return $this->mPreferredVariant
;
150 # FIXME rewrite code for parsing http header. The current code
151 # is written specific for detecting zh- variants
152 if( !$this->mPreferredVariant
) {
153 // see if some supported language variant is set in the
154 // http header, but we don't set the mPreferredVariant
155 // variable in case this is called before the user's
156 // preference is loaded
157 $pv=$this->mMainLanguageCode
;
158 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
159 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
160 $zh = strstr($header, $pv.'-');
162 $pv = substr($zh,0,5);
165 // don't try to return bad variant
166 if(in_array( $pv, $this->mVariants
))
170 return $this->mMainLanguageCode
;
175 * dictionary-based conversion
177 * @param string $text the text to be converted
178 * @param string $toVariant the target language code
179 * @return string the converted text
182 function autoConvert($text, $toVariant=false) {
183 $fname="LanguageConverter::autoConvert";
185 wfProfileIn( $fname );
187 if(!$this->mTablesLoaded
)
191 $toVariant = $this->getPreferredVariant();
192 if(!in_array($toVariant, $this->mVariants
))
195 /* we convert everything except:
196 1. html markups (anything between < and >)
198 3. place holders created by the parser
201 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
202 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
206 // this one is needed when the text is inside an html markup
207 $htmlfix = '|<[^>]+$|^[^<>]*>';
209 // disable convert to variants between <code></code> tags
210 $codefix = '<code>.+?<\/code>|';
211 // disable convertsion of <script type="text/javascript"> ... </script>
212 $scriptfix = '<script.*?>.*?<\/script>|';
213 // disable conversion of <pre xxxx> ... </pre>
214 $prefix = '<pre.*?>.*?<\/pre>|';
216 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
218 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
220 $m = array_shift($matches);
222 $ret = $this->translate($m[0], $toVariant);
223 $mstart = $m[1]+
strlen($m[0]);
224 foreach($matches as $m) {
225 $ret .= substr($text, $mstart, $m[1]-$mstart);
226 $ret .= $this->translate($m[0], $toVariant);
227 $mstart = $m[1] +
strlen($m[0]);
229 wfProfileOut( $fname );
234 * Translate a string to a variant
235 * Doesn't process markup or do any of that other stuff, for that use convert()
237 * @param string $text Text to convert
238 * @param string $variant Variant language code
239 * @return string Translated text
242 function translate( $text, $variant ) {
243 wfProfileIn( __METHOD__
);
244 if( !$this->mTablesLoaded
)
246 $text = $this->mTables
[$variant]->replace( $text );
247 wfProfileOut( __METHOD__
);
252 * convert text to all supported variants
254 * @param string $text the text to be converted
255 * @return array of string
258 function autoConvertToAllVariants($text) {
259 $fname="LanguageConverter::autoConvertToAllVariants";
260 wfProfileIn( $fname );
261 if( !$this->mTablesLoaded
)
265 foreach($this->mVariants
as $variant) {
266 $ret[$variant] = $this->translate($text, $variant);
269 wfProfileOut( $fname );
274 * convert link text to all supported variants
276 * @param string $text the text to be converted
277 * @return array of string
280 function convertLinkToAllVariants($text) {
281 if( !$this->mTablesLoaded
)
285 $tarray = explode($this->mMarkup
['begin'], $text);
286 $tfirst = array_shift($tarray);
288 foreach($this->mVariants
as $variant)
289 $ret[$variant] = $this->translate($tfirst,$variant);
291 foreach($tarray as $txt) {
292 $marked = explode($this->mMarkup
['end'], $txt, 2);
294 foreach($this->mVariants
as $variant){
295 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
296 if(array_key_exists(1, $marked))
297 $ret[$variant] .= $this->translate($marked[1],$variant);
307 * Convert text using a parser object for context
310 function parserConvert( $text, &$parser ) {
311 global $wgDisableLangConversion;
312 /* don't do anything if this is the conversion table */
313 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
314 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
319 if($wgDisableLangConversion)
322 $text = $this->convert( $text );
323 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
330 function applyManualConv($convRule,$variant){
331 if(!$variant) $variant = $this->getPreferredVariant();
332 $rules = $convRule->getRules();
333 $flags = $convRule->getFlags();
334 list($bidtable, $unidtable) = $convRule->getConvTable();
336 $is_title_flag = in_array('T', $flags);
337 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
339 $this->mTitleFromFlag
= true;
340 $this->mTitleDisplay
= $convRule->getTitle();
343 if($this->mManualLevel
[$variant]=='disable') return;
345 $is_remove_flag = !$is_title_flag && in_array('-', $flags);
346 $is_add_flag = !$is_remove_flag && in_array('+', $flags);
347 $is_bidMC = $this->mManualLevel
[$variant]=='bidirectional';
348 $is_unidMC = $this->mManualLevel
[$variant]=='unidirectional';
351 foreach($this->mVariants
as $v) {
352 /* for bidirectional array
353 fill in the missing variants, if any,
355 if($is_bidMC && !array_key_exists($v, $bidtable)) {
356 $vf = $convRule->getTextInBidtable($this->getVariantFallbacks($v) );
357 if($vf) $bidtable[$v] = $vf;
359 if($is_bidMC && array_key_exists($v,$bidtable)){
360 foreach($vmarked as $vo){
362 // -{A|zh:WordZh;zh-tw:WordTw}- or -{+|zh:WordZh;zh-tw:WordTw}-
363 // to introduce a custom mapping between
364 // words WordZh and WordTw in the whole text
366 $this->mTables
[$v]->setPair($bidtable[$vo], $bidtable[$v]);
367 $this->mTables
[$vo]->setPair($bidtable[$v], $bidtable[$vo]);
369 // use syntax -{-|zh:WordZh;zh-tw:WordTw}- to remove a conversion
370 // words WordZh and WordTw in the whole text
372 $this->mTables
[$v]->removePair($bidtable[$vo]);
373 $this->mTables
[$vo]->removePair($bidtable[$v]);
378 /*for unidirectional array
379 fill to convert tables */
380 if($is_unidMC && array_key_exists($v,$unidtable)){
381 if($is_add_flag)$this->mTables
[$v]->mergeArray($unidtable[$v]);
382 if($is_remove_flag)$this->mTables
[$v]->removeArray($unidtable[$v]);
391 function convertTitle($text){
392 // check for __NOTC__ tag
393 if( !$this->mDoTitleConvert
) {
394 $this->mTitleDisplay
= $text;
398 // use the title from the T flag if any
399 if($this->mTitleFromFlag
){
400 $this->mTitleFromFlag
= false;
401 return $this->mTitleDisplay
;
405 $isredir = $wgRequest->getText( 'redirect', 'yes' );
406 $action = $wgRequest->getText( 'action' );
407 if ( $isredir == 'no' ||
$action == 'edit' ) {
410 $this->mTitleDisplay
= $this->convert($text);
411 return $this->mTitleDisplay
;
416 * convert text to different variants of a language. the automatic
417 * conversion is done in autoConvert(). here we parse the text
418 * marked with -{}-, which specifies special conversions of the
419 * text that can not be accomplished in autoConvert()
421 * syntax of the markup:
422 * -{code1:text1;code2:text2;...}- or
423 * -{flags|code1:text1;code2:text2;...}- or
424 * -{text}- in which case no conversion should take place for text
426 * @param string $text text to be converted
427 * @param bool $isTitle whether this conversion is for the article title
428 * @return string converted text
431 function convert( $text , $isTitle=false) {
433 $mw =& MagicWord
::get( 'notitleconvert' );
434 if( $mw->matchAndRemove( $text ) )
435 $this->mDoTitleConvert
= false;
436 $mw =& MagicWord
::get( 'nocontentconvert' );
437 if( $mw->matchAndRemove( $text ) ) {
438 $this->mDoContentConvert
= false;
441 // no conversion if redirecting
442 $mw =& MagicWord
::get( 'redirect' );
443 if( $mw->matchStart( $text ))
446 // for title convertion
447 if ($isTitle) return $this->convertTitle($text);
449 $plang = $this->getPreferredVariant();
451 $tarray = explode($this->mMarkup
['begin'], $text);
452 $tfirst = array_shift($tarray);
453 if($this->mDoContentConvert
)
454 $text = $this->autoConvert($tfirst,$plang);
457 foreach($tarray as $txt) {
458 $marked = explode($this->mMarkup
['end'], $txt, 2);
460 // strip the flags from syntax like -{T| ... }-
461 $crule = new ConverterRule($marked[0],
462 $this->mMarkup
, $this->mFlags
,
463 $this->mVariantNames
,
464 $this->mDoContentConvert
,
465 $this->mDoTitleConvert
);
466 $crule->parse($plang,
467 $this->getVariantFallbacks($plang),
468 $this->mManualLevel
[$plang]=='disable');
469 $text .= $crule->getDisplay();
470 $this->applyManualConv($crule,$plang);
472 if(array_key_exists(1, $marked)){
473 if( $this->mDoContentConvert
)
474 $text .= $this->autoConvert($marked[1],$plang);
484 * if a language supports multiple variants, it is
485 * possible that non-existing link in one variant
486 * actually exists in another variant. this function
487 * tries to find it. See e.g. LanguageZh.php
489 * @param string $link the name of the link
490 * @param mixed $nt the title object of the link
491 * @return null the input parameters may be modified upon return
494 function findVariantLink( &$link, &$nt ) {
495 global $wgDisableLangConversion;
496 $linkBatch = new LinkBatch();
501 $ns = $nt->getNamespace();
503 $variants = $this->autoConvertToAllVariants($link);
504 if($variants == false) //give up
509 foreach( $variants as $v ) {
511 $varnt = Title
::newFromText( $v, $ns );
512 if(!is_null($varnt)){
513 $linkBatch->addObj($varnt);
519 // fetch all variants in single query
520 $linkBatch->execute();
522 foreach( $titles as $varnt ) {
523 if( $varnt->getArticleID() > 0 ) {
525 if( !$wgDisableLangConversion )
533 * returns language specific hash options
537 function getExtraHashOptions() {
538 $variant = $this->getPreferredVariant();
539 return '!' . $variant ;
543 * get title text as defined in the body of the article text
547 function getParsedTitle() {
548 return $this->mTitleDisplay
;
552 * a write lock to the cache
556 function lockCache() {
559 for($i=0; $i<30; $i++
) {
560 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
572 function unlockCache() {
574 $wgMemc->delete($this->mCacheKey
. "lock");
579 * Load default conversion tables
580 * This method must be implemented in derived class
584 function loadDefaultTables() {
585 $name = get_class($this);
586 wfDie("Must implement loadDefaultTables() method in class $name");
590 * load conversion tables either from the cache or the disk
593 function loadTables($fromcache=true) {
595 if( $this->mTablesLoaded
)
597 wfProfileIn( __METHOD__
);
598 $this->mTablesLoaded
= true;
599 $this->mTables
= false;
601 wfProfileIn( __METHOD__
.'-cache' );
602 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
603 wfProfileOut( __METHOD__
.'-cache' );
605 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
606 wfProfileIn( __METHOD__
.'-recache' );
607 // not in cache, or we need a fresh reload.
608 // we will first load the default tables
609 // then update them using things in MediaWiki:Zhconversiontable/*
610 $this->loadDefaultTables();
611 foreach($this->mVariants
as $var) {
612 $cached = $this->parseCachedTable($var);
613 $this->mTables
[$var]->mergeArray($cached);
616 $this->postLoadTables();
617 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
619 if($this->lockCache()) {
620 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
621 $this->unlockCache();
623 wfProfileOut( __METHOD__
.'-recache' );
625 wfProfileOut( __METHOD__
);
629 * Hook for post processig after conversion tables are loaded
632 function postLoadTables() {}
635 * Reload the conversion tables
639 function reloadTables() {
641 unset($this->mTables
);
642 $this->mTablesLoaded
= false;
643 $this->loadTables(false);
648 * parse the conversion table stored in the cache
650 * the tables should be in blocks of the following form:
657 * to make the tables more manageable, subpages are allowed
658 * and will be parsed recursively if $recursive=true
661 function parseCachedTable($code, $subpage='', $recursive=true) {
662 global $wgMessageCache;
663 static $parsed = array();
665 if(!is_object($wgMessageCache))
668 $key = 'Conversiontable/'.$code;
670 $key .= '/' . $subpage;
672 if(array_key_exists($key, $parsed))
675 if ( strpos( $code, '/' ) === false ) {
676 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
678 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
679 if ( $title && $title->exists() ) {
680 $article = new Article( $title );
681 $txt = $article->getContents();
687 // get all subpage links of the form
688 // [[MediaWiki:conversiontable/zh-xx/...|...]]
689 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
690 $subs = explode('[[', $txt);
692 foreach( $subs as $sub ) {
693 $link = explode(']]', $sub, 2);
694 if(count($link) != 2)
696 $b = explode('|', $link[0]);
697 $b = explode('/', trim($b[0]), 3);
703 if($b[0] == $linkhead && $b[1] == $code) {
704 $sublinks[] = $sublink;
709 // parse the mappings in this page
710 $blocks = explode($this->mMarkup
['begin'], $txt);
711 array_shift($blocks);
713 foreach($blocks as $block) {
714 $mappings = explode($this->mMarkup
['end'], $block, 2);
715 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
716 $table = explode( ';', $stripped );
717 foreach( $table as $t ) {
718 $m = explode( '=>', $t );
719 if( count( $m ) != 2)
721 // trim any trailling comments starting with '//'
722 $tt = explode('//', $m[1], 2);
723 $ret[trim($m[0])] = trim($tt[0]);
726 $parsed[$key] = true;
729 // recursively parse the subpages
731 foreach($sublinks as $link) {
732 $s = $this->parseCachedTable($code, $link, $recursive);
733 $ret = array_merge($ret, $s);
737 if ($this->mUcfirst
) {
738 foreach ($ret as $k => $v) {
739 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
746 * Enclose a string with the "no conversion" tag. This is used by
747 * various functions in the Parser
749 * @param string $text text to be tagged for no conversion
750 * @return string the tagged text
753 function markNoConversion($text, $noParse=false) {
754 # don't mark if already marked
755 if(strpos($text, $this->mMarkup
['begin']) ||
756 strpos($text, $this->mMarkup
['end']))
759 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
764 * convert the sorting key for category links. this should make different
765 * keys that are variants of each other map to the same key
767 function convertCategoryKey( $key ) {
771 * hook to refresh the cache of conversion tables when
772 * MediaWiki:conversiontable* is updated
775 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
776 $titleobj = $article->getTitle();
777 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
778 $title = $titleobj->getDBkey();
779 $t = explode('/', $title, 3);
781 if( $c > 1 && $t[0] == 'Conversiontable' ) {
782 if(in_array($t[1], $this->mVariants
)) {
783 $this->reloadTables();
791 * Armour rendered math against conversion
792 * Wrap math into rawoutput -{R| math }- syntax
795 function armourMath($text){
796 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
802 * parser for rules of language conversion , parse rules in -{ }- tag
804 * @author fdcn <fdcn64@gmail.com>
806 class ConverterRule
{
807 var $mText; // original text in -{text}-
812 var $mManualCodeError='<span style="color: red;">code error!</span>';
813 var $mDoTitleConvert=true, $mDoContentConvert=true;
814 var $ruleDisplay = '',$ruleTitle=false;
815 var $rules = '';// string $rule the text of the rule
816 var $flags = array();
817 var $bidtable = array();// array of the translation in each variant
818 var $unidtable = array();// array of the translation in each variant
823 * @param string $text the text between -{ and }-
824 * @param array $markup the supported markup for conversion
825 * @param array $flags the supported flags for conversion
826 * @param array $variantNames the names list of supported language
827 * @param bool $doTitleConvert if do title convert
828 * @param bool $doContentConvert if do content convert
831 function __construct($text,$markup,$flags,$variantNames,
832 $doTitleConvert=true, $doContentConvert=true){
833 $this->mText
= $text;
834 $this->mMarkup
= $markup;
835 $this->mFlags
= $flags;
836 $this->mVariantNames
= $variantNames;
837 $this->mDoTitleConvert
=$doTitleConvert;
838 $this->mDoContentConvert
=$doContentConvert;
842 * check if variants array in convert array
844 * @param string $variant Variant language code
845 * @return string Translated text
848 function getTextInBidtable($variants){
849 if(is_string($variants)){ $variants=array($variants); }
850 if(!is_array($variants)) return false;
851 foreach ($variants as $variant){
852 if(array_key_exists($variant, $this->bidtable
)){
853 return $this->bidtable
[$variant];
860 * Parse flags with syntax -{FLAG| ... }-
863 function parseFlags(){
864 $text = $this->mText
;
865 if(strlen($text) < 2 ) {
866 $this->flags
= array( 'R' );
867 $this->rules
= $text;
872 $tt = explode($this->mMarkup
['flagsep'], $text, 2);
874 if(count($tt) == 2) {
875 $f = explode($this->mMarkup
['varsep'], $tt[0]);
878 if(array_key_exists($ff, $this->mFlags
) &&
879 !in_array($this->mFlags
[$ff], $flags))
880 $flags[] = $this->mFlags
[$ff];
887 if( !in_array('R',$flags) ){
888 //FIXME: may cause trouble here...
889 //strip since it interferes with the parsing, plus,
890 //all spaces should be stripped in this tag anyway.
891 $rules = str_replace(' ', '', $rules);
892 $rules = str_replace('=>','=>',$rules);
896 if( in_array('R',$flags) ){
897 $flags = array('R');// remove other flags
898 } elseif ( in_array('N',$flags) ){
899 $flags = array('N');// remove other flags
900 } elseif ( in_array('-',$flags) ){
901 $flags = array('-');// remove other flags
902 } elseif (count($flags)==1 && $flags[0]=='T'){
904 } elseif ( in_array('H',$flags) ){
905 // replace A flag, and remove other flags except T
906 $temp=array('+','H');
907 if(in_array('T',$flags)) $temp[] = 'T';
908 if(in_array('D',$flags)) $temp[] = 'D';
911 if ( in_array('A',$flags)) {
915 if ( in_array('D',$flags) )
916 $flags=array_diff($flags,array('S'));
918 if ( count($flags)==0 )
925 * generate conversion table
928 function generateConvTable() {
929 $rules = $this->rules
;
930 $flags = $this->flags
;
932 $unidtable = array();
933 $choice = explode($this->mMarkup
['varsep'], $rules );
934 foreach($choice as $c) {
935 $v = explode($this->mMarkup
['codesep'], $c);
937 continue;// syntax error, skip
940 $u = explode($this->mMarkup
['unidsep'], $v);
943 } else if(count($u) == 2){
944 $from=trim($u[0]);$v=trim($u[1]);
945 if( array_key_exists($v,$unidtable) && !is_array($unidtable[$v]) )
946 $unidtable[$v]=array($from=>$to);
948 $unidtable[$v][$from]=$to;
950 // syntax error, pass
951 if (!array_key_exists($v,$this->mVariantNames
))
954 $this->bidtable
= $bidtable;
955 $this->unidtable
= $unidtable;
961 function getRulesDesc(){
963 foreach($this->bidtable
as $k => $v)
964 $text .= $this->mVariantNames
[$k].':'.$v.';';
965 foreach($this->unidtable
as $k => $a)
966 foreach($a as $from=>$to)
967 $text.=$from.'⇒'.$this->mVariantNames
[$k].':'.$to.';';
972 * Parse rules conversion
975 function getRuleConvertedStr($variant,$variantFallbacks,
976 $doConvert,$isMCDisable=false){
977 $bidtable = $this->bidtable
;
978 $unidtable = $this->unidtable
;
980 if( count($bidtable) +
count($unidtable) == 0 ){
982 } elseif ($doConvert){// the text converted
983 // display current variant in bidirectional array
984 $disp = $this->getTextInBidtable($variant);
985 // or display current variant in fallbacks
987 $disp = $this->getTextInBidtable($variantFallbacks);
988 // or display current variant in unidirectional array
989 if(!$disp && array_key_exists($variant,$unidtable)){
990 $disp = array_values($unidtable[$variant]);
993 // or display frist text under disable manual convert
994 if(!$disp && $isMCDisable) {
995 if(count($bidtable)>0){
996 $disp = array_values($bidtable);
999 $disp = array_values($unidtable);
1000 $disp = array_values($disp[0]);
1005 } else {// no convert
1006 return $this->rules
;
1011 * Parse rules and flags
1014 function parse($variant,$variantFallbacks,$isMCDisable=false){
1015 $this->parseFlags();
1016 $this->generateConvTable();
1018 $rules = $this->rules
;
1019 $flags = $this->flags
;
1021 if(count($this->bidtable
)==0 && count($this->unidtable
)==0
1022 && !in_array('N',$flags) && !in_array('T',$flags) )
1024 $this->flags
= $flags = array('R');
1027 if( in_array('R',$flags) ) {
1028 // if we don't do content convert, still strip the -{}- tags
1029 $this->ruleDisplay
= $rules;
1030 } elseif ( in_array('N',$flags) ){
1031 // proces N flag: output current variant name
1032 $this->ruleDisplay
= $this->mVariantNames
[trim($rules)];
1033 } elseif ( in_array('D',$flags) ){
1034 // proces D flag: output rules description
1035 $this->ruleDisplay
= $this->getRulesDesc();
1036 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1037 // proces H,- flag or T only: output nothing
1038 $this->ruleDisplay
= '';
1039 } elseif ( in_array('S',$flags) ){
1040 $this->ruleDisplay
= $this->getRuleConvertedStr(
1041 $variant,$variantFallbacks,
1042 $this->mDoContentConvert
,$isMCDisable);
1044 $this->ruleDisplay
= $this->mManualCodeError
;
1046 // proces T flag : output nothing
1047 if ( in_array('T',$flags) ) {
1048 $this->ruleTitle
= $this->getRuleConvertedStr(
1049 $variant,$variantFallbacks,
1050 $this->mDoTitleConvert
,$isMCDisable);
1055 * get display text on markup -{...}-
1056 * @param string $variant the current variant
1059 function getDisplay(){
1060 return $this->ruleDisplay
;
1063 * get converted title
1064 * @param string $variant the current variant
1067 function getTitle(){
1068 return $this->ruleTitle
;
1072 * get conversion table ( bidirectional and unidirectional conversion table )
1075 function getConvTable(){
1076 return array($this->bidtable
, $this->unidtable
);
1080 * get conversion rules string
1083 function getRules(){
1084 return $this->rules
;
1088 * get conversion flags
1091 function getFlags(){
1092 return $this->flags
;