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 $pv = substr($zh,0,5);
186 // don't try to return bad variant
187 if(in_array( $pv, $this->mVariants
))
191 return $this->mMainLanguageCode
;
196 * dictionary-based conversion
198 * @param string $text the text to be converted
199 * @param string $toVariant the target language code
200 * @return string the converted text
203 function autoConvert($text, $toVariant=false) {
204 $fname="LanguageConverter::autoConvert";
206 wfProfileIn( $fname );
208 if(!$this->mTablesLoaded
)
212 $toVariant = $this->getPreferredVariant();
213 if(!in_array($toVariant, $this->mVariants
))
216 /* we convert everything except:
217 1. html markups (anything between < and >)
219 3. place holders created by the parser
222 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
223 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
227 // this one is needed when the text is inside an html markup
228 $htmlfix = '|<[^>]+$|^[^<>]*>';
230 // disable convert to variants between <code></code> tags
231 $codefix = '<code>.+?<\/code>|';
232 // disable convertsion of <script type="text/javascript"> ... </script>
233 $scriptfix = '<script.*?>.*?<\/script>|';
234 // disable conversion of <pre xxxx> ... </pre>
235 $prefix = '<pre.*?>.*?<\/pre>|';
237 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
239 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
241 $m = array_shift($matches);
243 $ret = $this->translate($m[0], $toVariant);
244 $mstart = $m[1]+
strlen($m[0]);
245 foreach($matches as $m) {
246 $ret .= substr($text, $mstart, $m[1]-$mstart);
247 $ret .= $this->translate($m[0], $toVariant);
248 $mstart = $m[1] +
strlen($m[0]);
250 wfProfileOut( $fname );
255 * Translate a string to a variant
256 * Doesn't process markup or do any of that other stuff, for that use convert()
258 * @param string $text Text to convert
259 * @param string $variant Variant language code
260 * @return string Translated text
263 function translate( $text, $variant ) {
264 wfProfileIn( __METHOD__
);
265 if( !$this->mTablesLoaded
)
267 $text = $this->mTables
[$variant]->replace( $text );
268 wfProfileOut( __METHOD__
);
273 * convert text to all supported variants
275 * @param string $text the text to be converted
276 * @return array of string
279 function autoConvertToAllVariants($text) {
280 $fname="LanguageConverter::autoConvertToAllVariants";
281 wfProfileIn( $fname );
282 if( !$this->mTablesLoaded
)
286 foreach($this->mVariants
as $variant) {
287 $ret[$variant] = $this->translate($text, $variant);
290 wfProfileOut( $fname );
295 * convert link text to all supported variants
297 * @param string $text the text to be converted
298 * @return array of string
301 function convertLinkToAllVariants($text) {
302 if( !$this->mTablesLoaded
)
306 $tarray = explode($this->mMarkup
['begin'], $text);
307 $tfirst = array_shift($tarray);
309 foreach($this->mVariants
as $variant)
310 $ret[$variant] = $this->translate($tfirst,$variant);
312 foreach($tarray as $txt) {
313 $marked = explode($this->mMarkup
['end'], $txt, 2);
315 foreach($this->mVariants
as $variant){
316 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
317 if(array_key_exists(1, $marked))
318 $ret[$variant] .= $this->translate($marked[1],$variant);
328 * apply manual conversion
331 function applyManualConv($convRule){
332 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
333 $title = $convRule->getTitle();
335 $this->mTitleFromFlag
= true;
336 $this->mTitleDisplay
= $title;
339 //apply manual conversion table to global table
340 $convTable = $convRule->getConvTable();
341 $action = $convRule->getRulesAction();
342 foreach($convTable as $v=>$t) {
343 if( !in_array($v,$this->mVariants
) )continue;
345 $this->mTables
[$v]->mergeArray($t);
346 elseif ( $action=="remove" )
347 $this->mTables
[$v]->removeArray($t);
352 * Convert text using a parser object for context
355 function parserConvert( $text, &$parser ) {
356 global $wgDisableLangConversion;
357 /* don't do anything if this is the conversion table */
358 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
359 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
364 if($wgDisableLangConversion)
367 $text = $this->convert( $text );
368 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
376 function convertTitle($text){
377 global $wgDisableTitleConversion, $wgUser;
379 // check for global param and __NOTC__ tag
380 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
$wgUser->getOption('noconvertlink') == 1 ) {
381 $this->mTitleDisplay
= $text;
385 // use the title from the T flag if any
386 if($this->mTitleFromFlag
){
387 $this->mTitleFromFlag
= false;
388 return $this->mTitleDisplay
;
392 $isredir = $wgRequest->getText( 'redirect', 'yes' );
393 $action = $wgRequest->getText( 'action' );
394 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
395 if ( $isredir == 'no' ||
$action == 'edit' ||
$action == 'submit' ||
$linkconvert == 'no' ) {
398 $this->mTitleDisplay
= $this->convert($text);
399 return $this->mTitleDisplay
;
404 * convert text to different variants of a language. the automatic
405 * conversion is done in autoConvert(). here we parse the text
406 * marked with -{}-, which specifies special conversions of the
407 * text that can not be accomplished in autoConvert()
409 * syntax of the markup:
410 * -{code1:text1;code2:text2;...}- or
411 * -{flags|code1:text1;code2:text2;...}- or
412 * -{text}- in which case no conversion should take place for text
414 * @param string $text text to be converted
415 * @param bool $isTitle whether this conversion is for the article title
416 * @return string converted text
419 function convert( $text , $isTitle=false) {
421 $mw =& MagicWord
::get( 'notitleconvert' );
422 if( $mw->matchAndRemove( $text ) )
423 $this->mDoTitleConvert
= false;
424 $mw =& MagicWord
::get( 'nocontentconvert' );
425 if( $mw->matchAndRemove( $text ) ) {
426 $this->mDoContentConvert
= false;
429 // no conversion if redirecting
430 $mw =& MagicWord
::get( 'redirect' );
431 if( $mw->matchStart( $text ))
434 // for title convertion
435 if ($isTitle) return $this->convertTitle($text);
437 $plang = $this->getPreferredVariant();
438 $tarray = StringUtils
::explode($this->mMarkup
['end'], $text);
441 foreach($tarray as $txt) {
442 $marked = explode($this->mMarkup
['begin'], $txt, 2);
444 if( $this->mDoContentConvert
)
445 $text .= $this->autoConvert($marked[0],$plang);
449 if(array_key_exists(1, $marked)){
450 // strip the flags from syntax like -{T| ... }-
451 $crule = new ConverterRule($marked[1], $this);
452 $crule->parse($plang);
454 $text .= $crule->getDisplay();
455 $this->applyManualConv($crule);
458 // Reinsert the }- which wasn't part of anything
459 $text .= $this->mMarkup
['end'];
464 // Remove the last delimiter (wasn't real)
465 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
472 * if a language supports multiple variants, it is
473 * possible that non-existing link in one variant
474 * actually exists in another variant. this function
475 * tries to find it. See e.g. LanguageZh.php
477 * @param string $link the name of the link
478 * @param mixed $nt the title object of the link
479 * @return null the input parameters may be modified upon return
482 function findVariantLink( &$link, &$nt, $forTemplate = false ) {
483 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
484 $isredir = $wgRequest->getText( 'redirect', 'yes' );
485 $action = $wgRequest->getText( 'action' );
486 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
487 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
488 $linkBatch = new LinkBatch();
492 if ( $disableLinkConversion ||
( !$forTemplate && ( $isredir == 'no' ||
$action == 'edit'
493 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) ) {
498 $ns = $nt->getNamespace();
500 $variants = $this->autoConvertToAllVariants($link);
501 if($variants == false) //give up
506 foreach( $variants as $v ) {
508 $varnt = Title
::newFromText( $v, $ns );
509 if(!is_null($varnt)){
510 $linkBatch->addObj($varnt);
516 // fetch all variants in single query
517 $linkBatch->execute();
519 foreach( $titles as $varnt ) {
520 if( $varnt->getArticleID() > 0 ) {
529 * returns language specific hash options
533 function getExtraHashOptions() {
534 $variant = $this->getPreferredVariant();
535 return '!' . $variant ;
539 * get title text as defined in the body of the article text
543 function getParsedTitle() {
544 return $this->mTitleDisplay
;
548 * a write lock to the cache
552 function lockCache() {
555 for($i=0; $i<30; $i++
) {
556 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
568 function unlockCache() {
570 $wgMemc->delete($this->mCacheKey
. "lock");
575 * Load default conversion tables
576 * This method must be implemented in derived class
580 function loadDefaultTables() {
581 $name = get_class($this);
582 wfDie("Must implement loadDefaultTables() method in class $name");
586 * load conversion tables either from the cache or the disk
589 function loadTables($fromcache=true) {
591 if( $this->mTablesLoaded
)
593 wfProfileIn( __METHOD__
);
594 $this->mTablesLoaded
= true;
595 $this->mTables
= false;
597 wfProfileIn( __METHOD__
.'-cache' );
598 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
599 wfProfileOut( __METHOD__
.'-cache' );
601 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
602 wfProfileIn( __METHOD__
.'-recache' );
603 // not in cache, or we need a fresh reload.
604 // we will first load the default tables
605 // then update them using things in MediaWiki:Zhconversiontable/*
606 $this->loadDefaultTables();
607 foreach($this->mVariants
as $var) {
608 $cached = $this->parseCachedTable($var);
609 $this->mTables
[$var]->mergeArray($cached);
612 $this->postLoadTables();
613 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
615 if($this->lockCache()) {
616 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
617 $this->unlockCache();
619 wfProfileOut( __METHOD__
.'-recache' );
621 wfProfileOut( __METHOD__
);
625 * Hook for post processig after conversion tables are loaded
628 function postLoadTables() {}
631 * Reload the conversion tables
635 function reloadTables() {
637 unset($this->mTables
);
638 $this->mTablesLoaded
= false;
639 $this->loadTables(false);
644 * parse the conversion table stored in the cache
646 * the tables should be in blocks of the following form:
653 * to make the tables more manageable, subpages are allowed
654 * and will be parsed recursively if $recursive=true
657 function parseCachedTable($code, $subpage='', $recursive=true) {
658 global $wgMessageCache;
659 static $parsed = array();
661 if(!is_object($wgMessageCache))
664 $key = 'Conversiontable/'.$code;
666 $key .= '/' . $subpage;
668 if(array_key_exists($key, $parsed))
671 if ( strpos( $code, '/' ) === false ) {
672 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
674 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
675 if ( $title && $title->exists() ) {
676 $article = new Article( $title );
677 $txt = $article->getContents();
683 // get all subpage links of the form
684 // [[MediaWiki:conversiontable/zh-xx/...|...]]
685 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
686 $subs = explode('[[', $txt);
688 foreach( $subs as $sub ) {
689 $link = explode(']]', $sub, 2);
690 if(count($link) != 2)
692 $b = explode('|', $link[0]);
693 $b = explode('/', trim($b[0]), 3);
699 if($b[0] == $linkhead && $b[1] == $code) {
700 $sublinks[] = $sublink;
705 // parse the mappings in this page
706 $blocks = explode($this->mMarkup
['begin'], $txt);
707 array_shift($blocks);
709 foreach($blocks as $block) {
710 $mappings = explode($this->mMarkup
['end'], $block, 2);
711 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
712 $table = explode( ';', $stripped );
713 foreach( $table as $t ) {
714 $m = explode( '=>', $t );
715 if( count( $m ) != 2)
717 // trim any trailling comments starting with '//'
718 $tt = explode('//', $m[1], 2);
719 $ret[trim($m[0])] = trim($tt[0]);
722 $parsed[$key] = true;
725 // recursively parse the subpages
727 foreach($sublinks as $link) {
728 $s = $this->parseCachedTable($code, $link, $recursive);
729 $ret = array_merge($ret, $s);
733 if ($this->mUcfirst
) {
734 foreach ($ret as $k => $v) {
735 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
742 * Enclose a string with the "no conversion" tag. This is used by
743 * various functions in the Parser
745 * @param string $text text to be tagged for no conversion
746 * @return string the tagged text
749 function markNoConversion($text, $noParse=false) {
750 # don't mark if already marked
751 if(strpos($text, $this->mMarkup
['begin']) ||
752 strpos($text, $this->mMarkup
['end']))
755 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
760 * convert the sorting key for category links. this should make different
761 * keys that are variants of each other map to the same key
763 function convertCategoryKey( $key ) {
767 * hook to refresh the cache of conversion tables when
768 * MediaWiki:conversiontable* is updated
771 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
772 $titleobj = $article->getTitle();
773 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
774 $title = $titleobj->getDBkey();
775 $t = explode('/', $title, 3);
777 if( $c > 1 && $t[0] == 'Conversiontable' ) {
778 if(in_array($t[1], $this->mVariants
)) {
779 $this->reloadTables();
787 * Armour rendered math against conversion
788 * Wrap math into rawoutput -{R| math }- syntax
791 function armourMath($text){
792 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
798 * parser for rules of language conversion , parse rules in -{ }- tag
800 * @author fdcn <fdcn64@gmail.com>
802 class ConverterRule
{
803 var $mText; // original text in -{text}-
804 var $mConverter; // LanguageConverter object
805 var $mManualCodeError='<strong class="error">code error!</strong>';
806 var $mRuleDisplay = '',$mRuleTitle=false;
807 var $mRules = '';// string : the text of the rules
808 var $mRulesAction = 'none';
809 var $mFlags = array();
810 var $mConvTable = array();
811 var $mBidtable = array();// array of the translation in each variant
812 var $mUnidtable = array();// array of the translation in each variant
817 * @param string $text the text between -{ and }-
818 * @param object $converter a LanguageConverter object
821 function __construct($text,$converter){
822 $this->mText
= $text;
823 $this->mConverter
=$converter;
824 foreach($converter->mVariants
as $v){
825 $this->mConvTable
[$v]=array();
830 * check if variants array in convert array
832 * @param string $variant Variant language code
833 * @return string Translated text
836 function getTextInBidtable($variants){
837 if(is_string($variants)){ $variants=array($variants); }
838 if(!is_array($variants)) return false;
839 foreach ($variants as $variant){
840 if(array_key_exists($variant, $this->mBidtable
)){
841 return $this->mBidtable
[$variant];
848 * Parse flags with syntax -{FLAG| ... }-
851 function parseFlags(){
852 $text = $this->mText
;
853 if(strlen($text) < 2 ) {
854 $this->mFlags
= array( 'R' );
855 $this->mRules
= $text;
860 $markup = $this->mConverter
->mMarkup
;
861 $validFlags = $this->mConverter
->mFlags
;
863 $tt = explode($markup['flagsep'], $text, 2);
864 if(count($tt) == 2) {
865 $f = explode($markup['varsep'], $tt[0]);
868 if(array_key_exists($ff, $validFlags) &&
869 !in_array($validFlags[$ff], $flags))
870 $flags[] = $validFlags[$ff];
878 if( in_array('R',$flags) ){
879 $flags = array('R');// remove other flags
880 } elseif ( in_array('N',$flags) ){
881 $flags = array('N');// remove other flags
882 } elseif ( in_array('-',$flags) ){
883 $flags = array('-');// remove other flags
884 } elseif (count($flags)==1 && $flags[0]=='T'){
886 } elseif ( in_array('H',$flags) ){
887 // replace A flag, and remove other flags except T
888 $temp=array('+','H');
889 if(in_array('T',$flags)) $temp[] = 'T';
890 if(in_array('D',$flags)) $temp[] = 'D';
893 if ( in_array('A',$flags)) {
897 if ( in_array('D',$flags) )
898 $flags=array_diff($flags,array('S'));
900 if ( count($flags)==0 )
902 $this->mRules
=$rules;
903 $this->mFlags
=$flags;
907 * generate conversion table
910 function parseRules() {
911 $rules = $this->mRules
;
912 $flags = $this->mFlags
;
914 $unidtable = array();
915 $markup = $this->mConverter
->mMarkup
;
917 $choice = explode($markup['varsep'], $rules );
918 foreach($choice as $c) {
919 $v = explode($markup['codesep'], $c);
921 continue;// syntax error, skip
924 $u = explode($markup['unidsep'], $v);
927 } else if(count($u) == 2){
928 $from=trim($u[0]);$v=trim($u[1]);
929 if( array_key_exists($v,$unidtable) && !is_array($unidtable[$v]) )
930 $unidtable[$v]=array($from=>$to);
932 $unidtable[$v][$from]=$to;
934 // syntax error, pass
935 if (!array_key_exists($v,$this->mConverter
->mVariantNames
)){
937 $unidtable = array();
941 $this->mBidtable
= $bidtable;
942 $this->mUnidtable
= $unidtable;
948 function getRulesDesc(){
949 $codesep = $this->mConverter
->mDescCodeSep
;
950 $varsep = $this->mConverter
->mDescVarSep
;
952 foreach($this->mBidtable
as $k => $v)
953 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
954 foreach($this->mUnidtable
as $k => $a)
955 foreach($a as $from=>$to)
956 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
961 * Parse rules conversion
964 function getRuleConvertedStr($variant,$doConvert){
965 $bidtable = $this->mBidtable
;
966 $unidtable = $this->mUnidtable
;
968 if( count($bidtable) +
count($unidtable) == 0 ){
969 return $this->mRules
;
970 } elseif ($doConvert){// the text converted
971 // display current variant in bidirectional array
972 $disp = $this->getTextInBidtable($variant);
973 // or display current variant in fallbacks
975 $disp = $this->getTextInBidtable(
976 $this->mConverter
->getVariantFallbacks($variant));
977 // or display current variant in unidirectional array
978 if(!$disp && array_key_exists($variant,$unidtable)){
979 $disp = array_values($unidtable[$variant]);
982 // or display frist text under disable manual convert
983 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
984 if(count($bidtable)>0){
985 $disp = array_values($bidtable);
988 $disp = array_values($unidtable);
989 $disp = array_values($disp[0]);
994 } else {// no convert
995 return $this->mRules
;
1000 * generate conversion table for all text
1003 function generateConvTable(){
1004 $flags = $this->mFlags
;
1005 $bidtable = $this->mBidtable
;
1006 $unidtable = $this->mUnidtable
;
1007 $manLevel = $this->mConverter
->mManualLevel
;
1010 foreach($this->mConverter
->mVariants
as $v) {
1011 /* for bidirectional array
1012 fill in the missing variants, if any,
1014 if(!array_key_exists($v, $bidtable)) {
1015 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
1016 $vf = $this->getTextInBidtable($variantFallbacks);
1017 if($vf) $bidtable[$v] = $vf;
1020 if(array_key_exists($v,$bidtable)){
1021 foreach($vmarked as $vo){
1022 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1023 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1024 // to introduce a custom mapping between
1025 // words WordZh and WordTw in the whole text
1026 if($manLevel[$v]=='bidirectional'){
1027 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1029 if($manLevel[$vo]=='bidirectional'){
1030 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1035 /*for unidirectional array
1036 fill to convert tables */
1037 $allow_unid = $manLevel[$v]=='bidirectional'
1038 ||
$manLevel[$v]=='unidirectional';
1039 if($allow_unid && array_key_exists($v,$unidtable)){
1040 $ct=$this->mConvTable
[$v];
1041 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1047 * Parse rules and flags
1050 function parse($variant){
1051 if(!$variant) $variant = $this->mConverter
->getPreferredVariant();
1053 $this->parseFlags();
1054 $flags = $this->mFlags
;
1056 if( !in_array('R',$flags) ||
!in_array('N',$flags) ){
1057 //FIXME: may cause trouble here...
1058 //strip since it interferes with the parsing, plus,
1059 //all spaces should be stripped in this tag anyway.
1060 $this->mRules
= str_replace(' ', '', $this->mRules
);
1061 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1062 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1064 $this->parseRules();
1066 $rules = $this->mRules
;
1068 if(count($this->mBidtable
)==0 && count($this->mUnidtable
)==0){
1069 if(in_array('+',$flags) ||
in_array('-',$flags))
1070 // fill all variants if text in -{A/H/-|text} without rules
1071 foreach($this->mConverter
->mVariants
as $v)
1072 $this->mBidtable
[$v] = $rules;
1073 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1074 $this->mFlags
= $flags = array('R');
1077 if( in_array('R',$flags) ) {
1078 // if we don't do content convert, still strip the -{}- tags
1079 $this->mRuleDisplay
= $rules;
1080 } elseif ( in_array('N',$flags) ){
1081 // proces N flag: output current variant name
1082 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1083 } elseif ( in_array('D',$flags) ){
1084 // proces D flag: output rules description
1085 $this->mRuleDisplay
= $this->getRulesDesc();
1086 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1087 // proces H,- flag or T only: output nothing
1088 $this->mRuleDisplay
= '';
1089 } elseif ( in_array('S',$flags) ){
1090 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1091 $this->mConverter
->mDoContentConvert
);
1093 $this->mRuleDisplay
= $this->mManualCodeError
;
1096 if ( in_array('T',$flags) ) {
1097 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1098 $this->mConverter
->mDoTitleConvert
);
1101 if (in_array('-', $flags))
1102 $this->mRulesAction
='remove';
1103 if (in_array('+', $flags))
1104 $this->mRulesAction
='add';
1106 $this->generateConvTable();
1112 function hasRules(){
1117 * get display text on markup -{...}-
1120 function getDisplay(){
1121 return $this->mRuleDisplay
;
1124 * get converted title
1127 function getTitle(){
1128 return $this->mRuleTitle
;
1132 * return how deal with conversion rules
1135 function getRulesAction(){
1136 return $this->mRulesAction
;
1140 * get conversion table ( bidirectional and unidirectional conversion table )
1143 function getConvTable(){
1144 return $this->mConvTable
;
1148 * get conversion rules string
1151 function getRules(){
1152 return $this->mRules
;
1156 * get conversion flags
1159 function getFlags(){
1160 return $this->mFlags
;