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
129 $defaultUserLang = $wgUser->getOption( 'language' );
131 $defaultUserLang = $this->mMainLanguageCode
;
132 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
133 // see if interface language is same as content, if not, prevent conversion
134 if( ! in_array( $userLang, $this->mVariants
) ){
135 $this->mPreferredVariant
= $this->mMainLanguageCode
; // no conversion
136 return $this->mPreferredVariant
;
139 // see if the preference is set in the request
140 $req = $wgRequest->getText( 'variant' );
141 if( in_array( $req, $this->mVariants
) ) {
142 $this->mPreferredVariant
= $req;
146 // check the syntax /code/ArticleTitle
147 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
148 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
149 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
150 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
151 if(in_array($scriptBase,$this->mVariants
)){
152 $this->mPreferredVariant
= $scriptBase;
153 return $this->mPreferredVariant
;
157 // get language variant preference from logged in users
158 // Don't call this on stub objects because that causes infinite
159 // recursion during initialisation
160 if( $fromUser && $wgUser->isLoggedIn() ) {
161 $this->mPreferredVariant
= $wgUser->getOption('variant');
162 return $this->mPreferredVariant
;
165 // see if default variant is globaly set
166 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
167 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
168 return $this->mPreferredVariant
;
171 # FIXME rewrite code for parsing http header. The current code
172 # is written specific for detecting zh- variants
173 if( !$this->mPreferredVariant
) {
174 // see if some supported language variant is set in the
175 // http header, but we don't set the mPreferredVariant
176 // variable in case this is called before the user's
177 // preference is loaded
178 $pv=$this->mMainLanguageCode
;
179 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
180 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
181 $zh = strstr($header, $pv.'-');
183 $ary = split("[,;]",$zh);
187 // don't try to return bad variant
188 if(in_array( $pv, $this->mVariants
))
192 return $this->mMainLanguageCode
;
197 * dictionary-based conversion
199 * @param string $text the text to be converted
200 * @param string $toVariant the target language code
201 * @return string the converted text
204 function autoConvert($text, $toVariant=false) {
205 $fname="LanguageConverter::autoConvert";
207 wfProfileIn( $fname );
209 if(!$this->mTablesLoaded
)
213 $toVariant = $this->getPreferredVariant();
214 if(!in_array($toVariant, $this->mVariants
))
217 /* we convert everything except:
218 1. html markups (anything between < and >)
220 3. place holders created by the parser
223 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
224 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
228 // this one is needed when the text is inside an html markup
229 $htmlfix = '|<[^>]+$|^[^<>]*>';
231 // disable convert to variants between <code></code> tags
232 $codefix = '<code>.+?<\/code>|';
233 // disable convertsion of <script type="text/javascript"> ... </script>
234 $scriptfix = '<script.*?>.*?<\/script>|';
235 // disable conversion of <pre xxxx> ... </pre>
236 $prefix = '<pre.*?>.*?<\/pre>|';
238 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
240 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
242 $m = array_shift($matches);
244 $ret = $this->translate($m[0], $toVariant);
245 $mstart = $m[1]+
strlen($m[0]);
246 foreach($matches as $m) {
247 $ret .= substr($text, $mstart, $m[1]-$mstart);
248 $ret .= $this->translate($m[0], $toVariant);
249 $mstart = $m[1] +
strlen($m[0]);
251 wfProfileOut( $fname );
256 * Translate a string to a variant
257 * Doesn't process markup or do any of that other stuff, for that use convert()
259 * @param string $text Text to convert
260 * @param string $variant Variant language code
261 * @return string Translated text
264 function translate( $text, $variant ) {
265 wfProfileIn( __METHOD__
);
266 if( !$this->mTablesLoaded
)
268 $text = $this->mTables
[$variant]->replace( $text );
269 wfProfileOut( __METHOD__
);
274 * convert text to all supported variants
276 * @param string $text the text to be converted
277 * @return array of string
280 function autoConvertToAllVariants($text) {
281 $fname="LanguageConverter::autoConvertToAllVariants";
282 wfProfileIn( $fname );
283 if( !$this->mTablesLoaded
)
287 foreach($this->mVariants
as $variant) {
288 $ret[$variant] = $this->translate($text, $variant);
291 wfProfileOut( $fname );
296 * convert link text to all supported variants
298 * @param string $text the text to be converted
299 * @return array of string
302 function convertLinkToAllVariants($text) {
303 if( !$this->mTablesLoaded
)
307 $tarray = explode($this->mMarkup
['begin'], $text);
308 $tfirst = array_shift($tarray);
310 foreach($this->mVariants
as $variant)
311 $ret[$variant] = $this->translate($tfirst,$variant);
313 foreach($tarray as $txt) {
314 $marked = explode($this->mMarkup
['end'], $txt, 2);
316 foreach($this->mVariants
as $variant){
317 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
318 if(array_key_exists(1, $marked))
319 $ret[$variant] .= $this->translate($marked[1],$variant);
329 * apply manual conversion
332 function applyManualConv($convRule){
333 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
334 $title = $convRule->getTitle();
336 $this->mTitleFromFlag
= true;
337 $this->mTitleDisplay
= $title;
340 //apply manual conversion table to global table
341 $convTable = $convRule->getConvTable();
342 $action = $convRule->getRulesAction();
343 foreach($convTable as $v=>$t) {
344 if( !in_array($v,$this->mVariants
) )continue;
346 $this->mTables
[$v]->mergeArray($t);
347 elseif ( $action=="remove" )
348 $this->mTables
[$v]->removeArray($t);
353 * Convert text using a parser object for context
356 function parserConvert( $text, &$parser ) {
357 global $wgDisableLangConversion;
358 /* don't do anything if this is the conversion table */
359 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
360 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
365 if($wgDisableLangConversion)
368 $text = $this->convert( $text );
369 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
377 function convertTitle($text){
378 global $wgDisableTitleConversion, $wgUser;
380 // check for global param and __NOTC__ tag
381 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
$wgUser->getOption('noconvertlink') == 1 ) {
382 $this->mTitleDisplay
= $text;
386 // use the title from the T flag if any
387 if($this->mTitleFromFlag
){
388 $this->mTitleFromFlag
= false;
389 return $this->mTitleDisplay
;
393 $isredir = $wgRequest->getText( 'redirect', 'yes' );
394 $action = $wgRequest->getText( 'action' );
395 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
396 if ( $isredir == 'no' ||
$action == 'edit' ||
$action == 'submit' ||
$linkconvert == 'no' ) {
399 $this->mTitleDisplay
= $this->convert($text);
400 return $this->mTitleDisplay
;
405 * convert text to different variants of a language. the automatic
406 * conversion is done in autoConvert(). here we parse the text
407 * marked with -{}-, which specifies special conversions of the
408 * text that can not be accomplished in autoConvert()
410 * syntax of the markup:
411 * -{code1:text1;code2:text2;...}- or
412 * -{flags|code1:text1;code2:text2;...}- or
413 * -{text}- in which case no conversion should take place for text
415 * @param string $text text to be converted
416 * @param bool $isTitle whether this conversion is for the article title
417 * @return string converted text
420 function convert( $text , $isTitle=false) {
422 $mw =& MagicWord
::get( 'notitleconvert' );
423 if( $mw->matchAndRemove( $text ) )
424 $this->mDoTitleConvert
= false;
425 $mw =& MagicWord
::get( 'nocontentconvert' );
426 if( $mw->matchAndRemove( $text ) ) {
427 $this->mDoContentConvert
= false;
430 // no conversion if redirecting
431 $mw =& MagicWord
::get( 'redirect' );
432 if( $mw->matchStart( $text ))
435 // for title convertion
436 if ($isTitle) return $this->convertTitle($text);
438 $plang = $this->getPreferredVariant();
439 $tarray = StringUtils
::explode($this->mMarkup
['end'], $text);
442 foreach($tarray as $txt) {
443 $marked = explode($this->mMarkup
['begin'], $txt, 2);
445 if( $this->mDoContentConvert
)
446 $text .= $this->autoConvert($marked[0],$plang);
450 if(array_key_exists(1, $marked)){
451 // strip the flags from syntax like -{T| ... }-
452 $crule = new ConverterRule($marked[1], $this);
453 $crule->parse($plang);
455 $text .= $crule->getDisplay();
456 $this->applyManualConv($crule);
459 // Reinsert the }- which wasn't part of anything
460 $text .= $this->mMarkup
['end'];
465 // Remove the last delimiter (wasn't real)
466 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
473 * if a language supports multiple variants, it is
474 * possible that non-existing link in one variant
475 * actually exists in another variant. this function
476 * tries to find it. See e.g. LanguageZh.php
478 * @param string $link the name of the link
479 * @param mixed $nt the title object of the link
480 * @return null the input parameters may be modified upon return
483 function findVariantLink( &$link, &$nt, $forTemplate = false ) {
484 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
485 $isredir = $wgRequest->getText( 'redirect', 'yes' );
486 $action = $wgRequest->getText( 'action' );
487 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
488 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
489 $linkBatch = new LinkBatch();
493 if ( $disableLinkConversion ||
( !$forTemplate && ( $isredir == 'no' ||
$action == 'edit'
494 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) ) {
499 $ns = $nt->getNamespace();
501 $variants = $this->autoConvertToAllVariants($link);
502 if($variants == false) //give up
507 foreach( $variants as $v ) {
509 $varnt = Title
::newFromText( $v, $ns );
510 if(!is_null($varnt)){
511 $linkBatch->addObj($varnt);
517 // fetch all variants in single query
518 $linkBatch->execute();
520 foreach( $titles as $varnt ) {
521 if( $varnt->getArticleID() > 0 ) {
530 * returns language specific hash options
534 function getExtraHashOptions() {
535 $variant = $this->getPreferredVariant();
536 return '!' . $variant ;
540 * get title text as defined in the body of the article text
544 function getParsedTitle() {
545 return $this->mTitleDisplay
;
549 * a write lock to the cache
553 function lockCache() {
556 for($i=0; $i<30; $i++
) {
557 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
569 function unlockCache() {
571 $wgMemc->delete($this->mCacheKey
. "lock");
576 * Load default conversion tables
577 * This method must be implemented in derived class
581 function loadDefaultTables() {
582 $name = get_class($this);
583 wfDie("Must implement loadDefaultTables() method in class $name");
587 * load conversion tables either from the cache or the disk
590 function loadTables($fromcache=true) {
592 if( $this->mTablesLoaded
)
594 wfProfileIn( __METHOD__
);
595 $this->mTablesLoaded
= true;
596 $this->mTables
= false;
598 wfProfileIn( __METHOD__
.'-cache' );
599 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
600 wfProfileOut( __METHOD__
.'-cache' );
602 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
603 wfProfileIn( __METHOD__
.'-recache' );
604 // not in cache, or we need a fresh reload.
605 // we will first load the default tables
606 // then update them using things in MediaWiki:Zhconversiontable/*
607 $this->loadDefaultTables();
608 foreach($this->mVariants
as $var) {
609 $cached = $this->parseCachedTable($var);
610 $this->mTables
[$var]->mergeArray($cached);
613 $this->postLoadTables();
614 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
616 if($this->lockCache()) {
617 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
618 $this->unlockCache();
620 wfProfileOut( __METHOD__
.'-recache' );
622 wfProfileOut( __METHOD__
);
626 * Hook for post processig after conversion tables are loaded
629 function postLoadTables() {}
632 * Reload the conversion tables
636 function reloadTables() {
638 unset($this->mTables
);
639 $this->mTablesLoaded
= false;
640 $this->loadTables(false);
645 * parse the conversion table stored in the cache
647 * the tables should be in blocks of the following form:
654 * to make the tables more manageable, subpages are allowed
655 * and will be parsed recursively if $recursive=true
658 function parseCachedTable($code, $subpage='', $recursive=true) {
659 global $wgMessageCache;
660 static $parsed = array();
662 if(!is_object($wgMessageCache))
665 $key = 'Conversiontable/'.$code;
667 $key .= '/' . $subpage;
669 if(array_key_exists($key, $parsed))
672 if ( strpos( $code, '/' ) === false ) {
673 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
675 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
676 if ( $title && $title->exists() ) {
677 $article = new Article( $title );
678 $txt = $article->getContents();
684 // get all subpage links of the form
685 // [[MediaWiki:conversiontable/zh-xx/...|...]]
686 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
687 $subs = explode('[[', $txt);
689 foreach( $subs as $sub ) {
690 $link = explode(']]', $sub, 2);
691 if(count($link) != 2)
693 $b = explode('|', $link[0]);
694 $b = explode('/', trim($b[0]), 3);
700 if($b[0] == $linkhead && $b[1] == $code) {
701 $sublinks[] = $sublink;
706 // parse the mappings in this page
707 $blocks = explode($this->mMarkup
['begin'], $txt);
708 array_shift($blocks);
710 foreach($blocks as $block) {
711 $mappings = explode($this->mMarkup
['end'], $block, 2);
712 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
713 $table = explode( ';', $stripped );
714 foreach( $table as $t ) {
715 $m = explode( '=>', $t );
716 if( count( $m ) != 2)
718 // trim any trailling comments starting with '//'
719 $tt = explode('//', $m[1], 2);
720 $ret[trim($m[0])] = trim($tt[0]);
723 $parsed[$key] = true;
726 // recursively parse the subpages
728 foreach($sublinks as $link) {
729 $s = $this->parseCachedTable($code, $link, $recursive);
730 $ret = array_merge($ret, $s);
734 if ($this->mUcfirst
) {
735 foreach ($ret as $k => $v) {
736 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
743 * Enclose a string with the "no conversion" tag. This is used by
744 * various functions in the Parser
746 * @param string $text text to be tagged for no conversion
747 * @return string the tagged text
750 function markNoConversion($text, $noParse=false) {
751 # don't mark if already marked
752 if(strpos($text, $this->mMarkup
['begin']) ||
753 strpos($text, $this->mMarkup
['end']))
756 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
761 * convert the sorting key for category links. this should make different
762 * keys that are variants of each other map to the same key
764 function convertCategoryKey( $key ) {
768 * hook to refresh the cache of conversion tables when
769 * MediaWiki:conversiontable* is updated
772 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
773 $titleobj = $article->getTitle();
774 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
775 $title = $titleobj->getDBkey();
776 $t = explode('/', $title, 3);
778 if( $c > 1 && $t[0] == 'Conversiontable' ) {
779 if(in_array($t[1], $this->mVariants
)) {
780 $this->reloadTables();
788 * Armour rendered math against conversion
789 * Wrap math into rawoutput -{R| math }- syntax
792 function armourMath($text){
793 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
799 * parser for rules of language conversion , parse rules in -{ }- tag
801 * @author fdcn <fdcn64@gmail.com>
803 class ConverterRule
{
804 var $mText; // original text in -{text}-
805 var $mConverter; // LanguageConverter object
806 var $mManualCodeError='<strong class="error">code error!</strong>';
807 var $mRuleDisplay = '',$mRuleTitle=false;
808 var $mRules = '';// string : the text of the rules
809 var $mRulesAction = 'none';
810 var $mFlags = array();
811 var $mConvTable = array();
812 var $mBidtable = array();// array of the translation in each variant
813 var $mUnidtable = array();// array of the translation in each variant
818 * @param string $text the text between -{ and }-
819 * @param object $converter a LanguageConverter object
822 function __construct($text,$converter){
823 $this->mText
= $text;
824 $this->mConverter
=$converter;
825 foreach($converter->mVariants
as $v){
826 $this->mConvTable
[$v]=array();
831 * check if variants array in convert array
833 * @param string $variant Variant language code
834 * @return string Translated text
837 function getTextInBidtable($variants){
838 if(is_string($variants)){ $variants=array($variants); }
839 if(!is_array($variants)) return false;
840 foreach ($variants as $variant){
841 if(array_key_exists($variant, $this->mBidtable
)){
842 return $this->mBidtable
[$variant];
849 * Parse flags with syntax -{FLAG| ... }-
852 function parseFlags(){
853 $text = $this->mText
;
854 if(strlen($text) < 2 ) {
855 $this->mFlags
= array( 'R' );
856 $this->mRules
= $text;
861 $markup = $this->mConverter
->mMarkup
;
862 $validFlags = $this->mConverter
->mFlags
;
864 $tt = explode($markup['flagsep'], $text, 2);
865 if(count($tt) == 2) {
866 $f = explode($markup['varsep'], $tt[0]);
869 if(array_key_exists($ff, $validFlags) &&
870 !in_array($validFlags[$ff], $flags))
871 $flags[] = $validFlags[$ff];
879 if( in_array('R',$flags) ){
880 $flags = array('R');// remove other flags
881 } elseif ( in_array('N',$flags) ){
882 $flags = array('N');// remove other flags
883 } elseif ( in_array('-',$flags) ){
884 $flags = array('-');// remove other flags
885 } elseif (count($flags)==1 && $flags[0]=='T'){
887 } elseif ( in_array('H',$flags) ){
888 // replace A flag, and remove other flags except T
889 $temp=array('+','H');
890 if(in_array('T',$flags)) $temp[] = 'T';
891 if(in_array('D',$flags)) $temp[] = 'D';
894 if ( in_array('A',$flags)) {
898 if ( in_array('D',$flags) )
899 $flags=array_diff($flags,array('S'));
901 if ( count($flags)==0 )
903 $this->mRules
=$rules;
904 $this->mFlags
=$flags;
908 * generate conversion table
911 function parseRules() {
912 $rules = $this->mRules
;
913 $flags = $this->mFlags
;
915 $unidtable = array();
916 $markup = $this->mConverter
->mMarkup
;
918 $choice = explode($markup['varsep'], $rules );
919 foreach($choice as $c) {
920 $v = explode($markup['codesep'], $c);
922 continue;// syntax error, skip
925 $u = explode($markup['unidsep'], $v);
928 } else if(count($u) == 2){
929 $from=trim($u[0]);$v=trim($u[1]);
930 if( array_key_exists($v,$unidtable) && !is_array($unidtable[$v]) )
931 $unidtable[$v]=array($from=>$to);
933 $unidtable[$v][$from]=$to;
935 // syntax error, pass
936 if (!array_key_exists($v,$this->mConverter
->mVariantNames
)){
938 $unidtable = array();
942 $this->mBidtable
= $bidtable;
943 $this->mUnidtable
= $unidtable;
949 function getRulesDesc(){
950 $codesep = $this->mConverter
->mDescCodeSep
;
951 $varsep = $this->mConverter
->mDescVarSep
;
953 foreach($this->mBidtable
as $k => $v)
954 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
955 foreach($this->mUnidtable
as $k => $a)
956 foreach($a as $from=>$to)
957 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
962 * Parse rules conversion
965 function getRuleConvertedStr($variant,$doConvert){
966 $bidtable = $this->mBidtable
;
967 $unidtable = $this->mUnidtable
;
969 if( count($bidtable) +
count($unidtable) == 0 ){
970 return $this->mRules
;
971 } elseif ($doConvert){// the text converted
972 // display current variant in bidirectional array
973 $disp = $this->getTextInBidtable($variant);
974 // or display current variant in fallbacks
976 $disp = $this->getTextInBidtable(
977 $this->mConverter
->getVariantFallbacks($variant));
978 // or display current variant in unidirectional array
979 if(!$disp && array_key_exists($variant,$unidtable)){
980 $disp = array_values($unidtable[$variant]);
983 // or display frist text under disable manual convert
984 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
985 if(count($bidtable)>0){
986 $disp = array_values($bidtable);
989 $disp = array_values($unidtable);
990 $disp = array_values($disp[0]);
995 } else {// no convert
996 return $this->mRules
;
1001 * generate conversion table for all text
1004 function generateConvTable(){
1005 $flags = $this->mFlags
;
1006 $bidtable = $this->mBidtable
;
1007 $unidtable = $this->mUnidtable
;
1008 $manLevel = $this->mConverter
->mManualLevel
;
1011 foreach($this->mConverter
->mVariants
as $v) {
1012 /* for bidirectional array
1013 fill in the missing variants, if any,
1015 if(!array_key_exists($v, $bidtable)) {
1016 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
1017 $vf = $this->getTextInBidtable($variantFallbacks);
1018 if($vf) $bidtable[$v] = $vf;
1021 if(array_key_exists($v,$bidtable)){
1022 foreach($vmarked as $vo){
1023 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1024 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1025 // to introduce a custom mapping between
1026 // words WordZh and WordTw in the whole text
1027 if($manLevel[$v]=='bidirectional'){
1028 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1030 if($manLevel[$vo]=='bidirectional'){
1031 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1036 /*for unidirectional array
1037 fill to convert tables */
1038 $allow_unid = $manLevel[$v]=='bidirectional'
1039 ||
$manLevel[$v]=='unidirectional';
1040 if($allow_unid && array_key_exists($v,$unidtable)){
1041 $ct=$this->mConvTable
[$v];
1042 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1048 * Parse rules and flags
1051 function parse($variant){
1052 if(!$variant) $variant = $this->mConverter
->getPreferredVariant();
1054 $this->parseFlags();
1055 $flags = $this->mFlags
;
1057 if( !in_array('R',$flags) ||
!in_array('N',$flags) ){
1058 //FIXME: may cause trouble here...
1059 //strip since it interferes with the parsing, plus,
1060 //all spaces should be stripped in this tag anyway.
1061 $this->mRules
= str_replace(' ', '', $this->mRules
);
1062 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1063 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1065 $this->parseRules();
1067 $rules = $this->mRules
;
1069 if(count($this->mBidtable
)==0 && count($this->mUnidtable
)==0){
1070 if(in_array('+',$flags) ||
in_array('-',$flags))
1071 // fill all variants if text in -{A/H/-|text} without rules
1072 foreach($this->mConverter
->mVariants
as $v)
1073 $this->mBidtable
[$v] = $rules;
1074 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1075 $this->mFlags
= $flags = array('R');
1078 if( in_array('R',$flags) ) {
1079 // if we don't do content convert, still strip the -{}- tags
1080 $this->mRuleDisplay
= $rules;
1081 } elseif ( in_array('N',$flags) ){
1082 // proces N flag: output current variant name
1083 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1084 } elseif ( in_array('D',$flags) ){
1085 // proces D flag: output rules description
1086 $this->mRuleDisplay
= $this->getRulesDesc();
1087 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1088 // proces H,- flag or T only: output nothing
1089 $this->mRuleDisplay
= '';
1090 } elseif ( in_array('S',$flags) ){
1091 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1092 $this->mConverter
->mDoContentConvert
);
1094 $this->mRuleDisplay
= $this->mManualCodeError
;
1097 if ( in_array('T',$flags) ) {
1098 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1099 $this->mConverter
->mDoTitleConvert
);
1102 if (in_array('-', $flags))
1103 $this->mRulesAction
='remove';
1104 if (in_array('+', $flags))
1105 $this->mRulesAction
='add';
1107 $this->generateConvTable();
1113 function hasRules(){
1118 * get display text on markup -{...}-
1121 function getDisplay(){
1122 return $this->mRuleDisplay
;
1125 * get converted title
1128 function getTitle(){
1129 return $this->mRuleTitle
;
1133 * return how deal with conversion rules
1136 function getRulesAction(){
1137 return $this->mRulesAction
;
1141 * get conversion table ( bidirectional and unidirectional conversion table )
1144 function getConvTable(){
1145 return $this->mConvTable
;
1149 * get conversion rules string
1152 function getRules(){
1153 return $this->mRules
;
1157 * get conversion flags
1160 function getFlags(){
1161 return $this->mFlags
;