4 * Contains the LanguageConverter class and ConverterRule class
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
12 * base class for language convert
15 * @author Zhengzhu Feng <zhengzhu@gmail.com>
16 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>, PhiLiP <philip.npc@gmail.com>
18 class LanguageConverter
{
19 var $mPreferredVariant='';
20 var $mMainLanguageCode;
21 var $mVariants, $mVariantFallbacks, $mVariantNames;
22 var $mTablesLoaded = false;
24 var $mManualAddTables;
25 var $mManualRemoveTables;
26 var $mTitleDisplay='';
27 var $mDoTitleConvert=true, $mDoContentConvert=true;
28 var $mManualLevel; // 'bidirectional' 'unidirectional' 'disable' for each variants
29 var $mTitleFromFlag = false;
34 var $mDescCodeSep = ':',$mDescVarSep = ';';
35 var $mUcfirst = false;
37 const CACHE_VERSION_KEY
= 'VERSION 6';
42 * @param string $maincode the main language code of this language
43 * @param array $variants the supported variants of this language
44 * @param array $variantfallback the fallback language of each variant
45 * @param array $markup array defining the markup used for manual conversion
46 * @param array $flags array defining the custom strings that maps to the flags
47 * @param array $manualLevel limit for supported variants
50 function __construct($langobj, $maincode,
52 $variantfallbacks=array(),
55 $manualLevel = array() ) {
56 $this->mLangObj
= $langobj;
57 $this->mMainLanguageCode
= $maincode;
58 $this->mVariants
= $variants;
59 $this->mVariantFallbacks
= $variantfallbacks;
60 global $wgLanguageNames;
61 $this->mVariantNames
= $wgLanguageNames;
62 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
66 'unidsep'=>'=>', //for unidirectional conversion
71 $this->mMarkup
= array_merge($m, $markup);
73 // 'S' show converted text
74 // '+' add rules for alltext
75 // 'E' the gave flags is error
76 // these flags above are reserved for program
77 'A'=>'A', // add rule for convert code (all text convert)
78 'T'=>'T', // title convert
79 'R'=>'R', // raw content
80 'D'=>'D', // convert description (subclass implement)
81 '-'=>'-', // remove convert (not implement)
82 'H'=>'H', // add rule for convert code (but no display in placed code )
83 'N'=>'N' // current variant name
85 $this->mFlags
= array_merge($f, $flags);
86 foreach( $this->mVariants
as $v) {
87 $this->mManualLevel
[$v]=array_key_exists($v,$manualLevel)
90 $this->mManualAddTables
[$v] = array();
91 $this->mManualRemoveTables
[$v] = array();
98 function getVariants() {
99 return $this->mVariants
;
103 * in case some variant is not defined in the markup, we need
104 * to have some fallback. for example, in zh, normally people
105 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
106 * when zh-sg is preferred but not defined, we will pick zh-hans
107 * in this case. right now this is only used by zh.
109 * @param string $v the language code of the variant
110 * @return string array the code of the fallback language or false if there is no fallback
113 function getVariantFallbacks($v) {
114 if( isset( $this->mVariantFallbacks
[$v] ) ) {
115 return $this->mVariantFallbacks
[$v];
117 return $this->mMainLanguageCode
;
121 * get preferred language variants.
122 * @param boolean $fromUser Get it from $wgUser's preferences
123 * @return string the preferred language code
126 function getPreferredVariant( $fromUser = true ) {
127 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
129 if($this->mPreferredVariant
)
130 return $this->mPreferredVariant
;
132 // figure out user lang without constructing wgLang to avoid infinite recursion
134 $defaultUserLang = $wgUser->getOption( 'language' );
136 $defaultUserLang = $this->mMainLanguageCode
;
137 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
138 // see if interface language is same as content, if not, prevent conversion
139 if( ! in_array( $userLang, $this->mVariants
) ){
140 $this->mPreferredVariant
= $this->mMainLanguageCode
; // no conversion
141 return $this->mPreferredVariant
;
144 // see if the preference is set in the request
145 $req = $wgRequest->getText( 'variant' );
146 if( in_array( $req, $this->mVariants
) ) {
147 $this->mPreferredVariant
= $req;
151 // check the syntax /code/ArticleTitle
152 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
153 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
154 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
155 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
156 if(in_array($scriptBase,$this->mVariants
)){
157 $this->mPreferredVariant
= $scriptBase;
158 return $this->mPreferredVariant
;
162 // get language variant preference from logged in users
163 // Don't call this on stub objects because that causes infinite
164 // recursion during initialisation
165 if( $fromUser && $wgUser->isLoggedIn() ) {
166 $this->mPreferredVariant
= $wgUser->getOption('variant');
167 return $this->mPreferredVariant
;
170 // see if default variant is globaly set
171 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
172 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
173 return $this->mPreferredVariant
;
176 # FIXME rewrite code for parsing http header. The current code
177 # is written specific for detecting zh- variants
178 if( !$this->mPreferredVariant
) {
179 // see if some supported language variant is set in the
180 // http header, but we don't set the mPreferredVariant
181 // variable in case this is called before the user's
182 // preference is loaded
183 $pv=$this->mMainLanguageCode
;
184 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
185 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
186 $zh = strstr($header, $pv.'-');
188 $ary = split("[,;]",$zh);
192 // don't try to return bad variant
193 if(in_array( $pv, $this->mVariants
))
197 return $this->mMainLanguageCode
;
202 * caption convert, base on preg_replace_callback
204 * to convert text in "title" or "alt", like '<img alt="text" ... '
205 * or '<span title="text" ... '
207 * @return string like ' alt="yyyy"' or ' title="yyyy"'
210 function captionConvert( $matches ) {
211 // we convert captions except URL
212 $toVariant = $this->getPreferredVariant();
213 $title = $matches[1];
215 if( !strpos( $text, '://' ) )
216 $text = $this->translate($text, $toVariant);
217 return " $title=\"$text\"";
221 * dictionary-based conversion
223 * @param string $text the text to be converted
224 * @param string $toVariant the target language code
225 * @return string the converted text
228 function autoConvert($text, $toVariant=false) {
229 $fname="LanguageConverter::autoConvert";
231 wfProfileIn( $fname );
233 if(!$this->mTablesLoaded
)
237 $toVariant = $this->getPreferredVariant();
238 if(!in_array($toVariant, $this->mVariants
))
241 /* we convert everything except:
242 1. html markups (anything between < and >)
244 3. place holders created by the parser
247 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
248 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
252 // this one is needed when the text is inside an html markup
253 $htmlfix = '|<[^>]+$|^[^<>]*>';
255 // disable convert to variants between <code></code> tags
256 $codefix = '<code>.+?<\/code>|';
257 // disable convertsion of <script type="text/javascript"> ... </script>
258 $scriptfix = '<script.*?>.*?<\/script>|';
259 // disable conversion of <pre xxxx> ... </pre>
260 $prefix = '<pre.*?>.*?<\/pre>|';
262 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
264 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
266 $m = array_shift($matches);
268 $ret = $this->translate($m[0], $toVariant);
269 $mstart = $m[1]+
strlen($m[0]);
271 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
272 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
273 foreach($matches as $m) {
274 $mark = substr($text, $mstart, $m[1]-$mstart);
275 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
277 $ret .= $this->translate($m[0], $toVariant);
278 $mstart = $m[1] +
strlen($m[0]);
280 wfProfileOut( $fname );
285 * Translate a string to a variant
286 * Doesn't process markup or do any of that other stuff, for that use convert()
288 * @param string $text Text to convert
289 * @param string $variant Variant language code
290 * @return string Translated text
293 function translate( $text, $variant ) {
294 wfProfileIn( __METHOD__
);
295 if( !$this->mTablesLoaded
)
297 $text = $this->mTables
[$variant]->replace( $text );
298 wfProfileOut( __METHOD__
);
303 * convert text to all supported variants
305 * @param string $text the text to be converted
306 * @return array of string
309 function autoConvertToAllVariants($text) {
310 $fname="LanguageConverter::autoConvertToAllVariants";
311 wfProfileIn( $fname );
312 if( !$this->mTablesLoaded
)
316 foreach($this->mVariants
as $variant) {
317 $ret[$variant] = $this->translate($text, $variant);
320 wfProfileOut( $fname );
325 * convert link text to all supported variants
327 * @param string $text the text to be converted
328 * @return array of string
331 function convertLinkToAllVariants($text) {
332 if( !$this->mTablesLoaded
)
336 $tarray = explode($this->mMarkup
['begin'], $text);
337 $tfirst = array_shift($tarray);
339 foreach($this->mVariants
as $variant)
340 $ret[$variant] = $this->translate($tfirst,$variant);
342 foreach($tarray as $txt) {
343 $marked = explode($this->mMarkup
['end'], $txt, 2);
345 foreach($this->mVariants
as $variant){
346 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
347 if(array_key_exists(1, $marked))
348 $ret[$variant] .= $this->translate($marked[1],$variant);
357 * prepare manual conversion table
360 function prepareManualConv($convRule){
361 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
362 $title = $convRule->getTitle();
364 $this->mTitleFromFlag
= true;
365 $this->mTitleDisplay
= $title;
368 //apply manual conversion table to global table
369 $convTable = $convRule->getConvTable();
370 $action = $convRule->getRulesAction();
371 foreach($convTable as $v=>$t) {
372 if( !in_array($v,$this->mVariants
) )continue;
373 if( $action=="add" ) {
374 foreach($t as $from=>$to) {
375 // more efficient than array_merge(), about 2.5 times.
376 $this->mManualAddTables
[$v][$from] = $to;
379 elseif ( $action=="remove" )
380 $this->mManualRemoveTables
[$v] = array_merge($this->mManualRemoveTables
[$v], $t);
385 * apply manual conversion from $this->mManualAddTables and $this->mManualRemoveTables
388 function applyManualConv(){
389 //apply manual conversion table to global table
390 foreach($this->mVariants
as $v) {
391 if (count($this->mManualAddTables
[$v]) > 0) {
392 $this->mTables
[$v]->mergeArray($this->mManualAddTables
[$v]);
394 if (count($this->mManualRemoveTables
[$v]) > 0)
395 $this->mTables
[$v]->removeArray($this->mManualRemoveTables
[$v]);
400 * Convert text using a parser object for context
403 function parserConvert( $text, &$parser ) {
404 global $wgDisableLangConversion;
405 /* don't do anything if this is the conversion table */
406 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
407 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
412 if($wgDisableLangConversion)
415 $text = $this->convert( $text );
416 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
424 function convertTitle($text){
425 global $wgDisableTitleConversion, $wgUser;
427 // check for global param and __NOTC__ tag
428 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
$wgUser->getOption('noconvertlink') == 1 ) {
429 $this->mTitleDisplay
= $text;
433 // use the title from the T flag if any
434 if($this->mTitleFromFlag
){
435 $this->mTitleFromFlag
= false;
436 return $this->mTitleDisplay
;
440 $isredir = $wgRequest->getText( 'redirect', 'yes' );
441 $action = $wgRequest->getText( 'action' );
442 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
443 if ( $isredir == 'no' ||
$action == 'edit' ||
$action == 'submit' ||
$linkconvert == 'no' ) {
446 $this->mTitleDisplay
= $this->convert($text);
447 return $this->mTitleDisplay
;
452 * convert text to different variants of a language. the automatic
453 * conversion is done in autoConvert(). here we parse the text
454 * marked with -{}-, which specifies special conversions of the
455 * text that can not be accomplished in autoConvert()
457 * syntax of the markup:
458 * -{code1:text1;code2:text2;...}- or
459 * -{flags|code1:text1;code2:text2;...}- or
460 * -{text}- in which case no conversion should take place for text
462 * @param string $text text to be converted
463 * @param bool $isTitle whether this conversion is for the article title
464 * @return string converted text
467 function convert( $text , $isTitle=false) {
469 $mw =& MagicWord
::get( 'notitleconvert' );
470 if( $mw->matchAndRemove( $text ) )
471 $this->mDoTitleConvert
= false;
472 $mw =& MagicWord
::get( 'nocontentconvert' );
473 if( $mw->matchAndRemove( $text ) ) {
474 $this->mDoContentConvert
= false;
477 // no conversion if redirecting
478 $mw =& MagicWord
::get( 'redirect' );
479 if( $mw->matchStart( $text ))
482 // for title convertion
483 if ($isTitle) return $this->convertTitle($text);
485 $plang = $this->getPreferredVariant();
486 $tarray = StringUtils
::explode($this->mMarkup
['end'], $text);
490 foreach($tarray as $txt) {
491 $marked = explode($this->mMarkup
['begin'], $txt, 2);
492 if (array_key_exists(1, $marked)) {
493 $crule = new ConverterRule($marked[1], $this);
494 $crule->parse($plang);
495 $marked[1] = $crule->getDisplay();
496 $this->prepareManualConv($crule);
499 $marked[0] .= $this->mMarkup
['end'];
500 array_push($marks, $marked);
502 $this->applyManualConv();
503 foreach ($marks as $marked) {
504 if( $this->mDoContentConvert
)
505 $text .= $this->autoConvert($marked[0],$plang);
508 if( array_key_exists(1, $marked) )
511 // Remove the last delimiter (wasn't real)
512 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
518 * if a language supports multiple variants, it is
519 * possible that non-existing link in one variant
520 * actually exists in another variant. this function
521 * tries to find it. See e.g. LanguageZh.php
523 * @param string $link the name of the link
524 * @param mixed $nt the title object of the link
525 * @return null the input parameters may be modified upon return
528 function findVariantLink( &$link, &$nt, $forTemplate = false ) {
529 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
530 $isredir = $wgRequest->getText( 'redirect', 'yes' );
531 $action = $wgRequest->getText( 'action' );
532 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
533 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
534 $linkBatch = new LinkBatch();
538 if ( $disableLinkConversion ||
( !$forTemplate && ( $isredir == 'no' ||
$action == 'edit'
539 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) ) {
544 $ns = $nt->getNamespace();
546 $variants = $this->autoConvertToAllVariants($link);
547 if($variants == false) //give up
552 foreach( $variants as $v ) {
554 $varnt = Title
::newFromText( $v, $ns );
555 if(!is_null($varnt)){
556 $linkBatch->addObj($varnt);
562 // fetch all variants in single query
563 $linkBatch->execute();
565 foreach( $titles as $varnt ) {
566 if( $varnt->getArticleID() > 0 ) {
575 * returns language specific hash options
579 function getExtraHashOptions() {
580 $variant = $this->getPreferredVariant();
581 return '!' . $variant ;
585 * get title text as defined in the body of the article text
589 function getParsedTitle() {
590 return $this->mTitleDisplay
;
594 * a write lock to the cache
598 function lockCache() {
601 for($i=0; $i<30; $i++
) {
602 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
614 function unlockCache() {
616 $wgMemc->delete($this->mCacheKey
. "lock");
621 * Load default conversion tables
622 * This method must be implemented in derived class
626 function loadDefaultTables() {
627 $name = get_class($this);
628 wfDie("Must implement loadDefaultTables() method in class $name");
632 * load conversion tables either from the cache or the disk
635 function loadTables($fromcache=true) {
637 if( $this->mTablesLoaded
)
639 wfProfileIn( __METHOD__
);
640 $this->mTablesLoaded
= true;
641 $this->mTables
= false;
643 wfProfileIn( __METHOD__
.'-cache' );
644 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
645 wfProfileOut( __METHOD__
.'-cache' );
647 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
648 wfProfileIn( __METHOD__
.'-recache' );
649 // not in cache, or we need a fresh reload.
650 // we will first load the default tables
651 // then update them using things in MediaWiki:Zhconversiontable/*
652 $this->loadDefaultTables();
653 foreach($this->mVariants
as $var) {
654 $cached = $this->parseCachedTable($var);
655 $this->mTables
[$var]->mergeArray($cached);
658 $this->postLoadTables();
659 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
661 if($this->lockCache()) {
662 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
663 $this->unlockCache();
665 wfProfileOut( __METHOD__
.'-recache' );
667 wfProfileOut( __METHOD__
);
671 * Hook for post processig after conversion tables are loaded
674 function postLoadTables() {}
677 * Reload the conversion tables
681 function reloadTables() {
683 unset($this->mTables
);
684 $this->mTablesLoaded
= false;
685 $this->loadTables(false);
690 * parse the conversion table stored in the cache
692 * the tables should be in blocks of the following form:
699 * to make the tables more manageable, subpages are allowed
700 * and will be parsed recursively if $recursive=true
703 function parseCachedTable($code, $subpage='', $recursive=true) {
704 global $wgMessageCache;
705 static $parsed = array();
707 if(!is_object($wgMessageCache))
710 $key = 'Conversiontable/'.$code;
712 $key .= '/' . $subpage;
714 if(array_key_exists($key, $parsed))
717 if ( strpos( $code, '/' ) === false ) {
718 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
720 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
721 if ( $title && $title->exists() ) {
722 $article = new Article( $title );
723 $txt = $article->getContents();
729 // get all subpage links of the form
730 // [[MediaWiki:conversiontable/zh-xx/...|...]]
731 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
732 $subs = explode('[[', $txt);
734 foreach( $subs as $sub ) {
735 $link = explode(']]', $sub, 2);
736 if(count($link) != 2)
738 $b = explode('|', $link[0]);
739 $b = explode('/', trim($b[0]), 3);
745 if($b[0] == $linkhead && $b[1] == $code) {
746 $sublinks[] = $sublink;
751 // parse the mappings in this page
752 $blocks = explode($this->mMarkup
['begin'], $txt);
753 array_shift($blocks);
755 foreach($blocks as $block) {
756 $mappings = explode($this->mMarkup
['end'], $block, 2);
757 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
758 $table = explode( ';', $stripped );
759 foreach( $table as $t ) {
760 $m = explode( '=>', $t );
761 if( count( $m ) != 2)
763 // trim any trailling comments starting with '//'
764 $tt = explode('//', $m[1], 2);
765 $ret[trim($m[0])] = trim($tt[0]);
768 $parsed[$key] = true;
771 // recursively parse the subpages
773 foreach($sublinks as $link) {
774 $s = $this->parseCachedTable($code, $link, $recursive);
775 $ret = array_merge($ret, $s);
779 if ($this->mUcfirst
) {
780 foreach ($ret as $k => $v) {
781 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
788 * Enclose a string with the "no conversion" tag. This is used by
789 * various functions in the Parser
791 * @param string $text text to be tagged for no conversion
792 * @return string the tagged text
795 function markNoConversion($text, $noParse=false) {
796 # don't mark if already marked
797 if(strpos($text, $this->mMarkup
['begin']) ||
798 strpos($text, $this->mMarkup
['end']))
801 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
806 * convert the sorting key for category links. this should make different
807 * keys that are variants of each other map to the same key
809 function convertCategoryKey( $key ) {
813 * hook to refresh the cache of conversion tables when
814 * MediaWiki:conversiontable* is updated
817 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
818 $titleobj = $article->getTitle();
819 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
820 $title = $titleobj->getDBkey();
821 $t = explode('/', $title, 3);
823 if( $c > 1 && $t[0] == 'Conversiontable' ) {
824 if(in_array($t[1], $this->mVariants
)) {
825 $this->reloadTables();
833 * Armour rendered math against conversion
834 * Wrap math into rawoutput -{R| math }- syntax
837 function armourMath($text){
838 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
844 * parser for rules of language conversion , parse rules in -{ }- tag
846 * @author fdcn <fdcn64@gmail.com>
848 class ConverterRule
{
849 var $mText; // original text in -{text}-
850 var $mConverter; // LanguageConverter object
851 var $mManualCodeError='<strong class="error">code error!</strong>';
852 var $mRuleDisplay = '',$mRuleTitle=false;
853 var $mRules = '';// string : the text of the rules
854 var $mRulesAction = 'none';
855 var $mFlags = array();
856 var $mConvTable = array();
857 var $mBidtable = array();// array of the translation in each variant
858 var $mUnidtable = array();// array of the translation in each variant
863 * @param string $text the text between -{ and }-
864 * @param object $converter a LanguageConverter object
867 function __construct($text,$converter){
868 $this->mText
= $text;
869 $this->mConverter
=$converter;
870 foreach($converter->mVariants
as $v){
871 $this->mConvTable
[$v]=array();
876 * check if variants array in convert array
878 * @param string $variant Variant language code
879 * @return string Translated text
882 function getTextInBidtable($variants){
883 if(is_string($variants)){ $variants=array($variants); }
884 if(!is_array($variants)) return false;
885 foreach ($variants as $variant){
886 if(array_key_exists($variant, $this->mBidtable
)){
887 return $this->mBidtable
[$variant];
894 * Parse flags with syntax -{FLAG| ... }-
897 function parseFlags(){
898 $text = $this->mText
;
899 if(strlen($text) < 2 ) {
900 $this->mFlags
= array( 'R' );
901 $this->mRules
= $text;
906 $markup = $this->mConverter
->mMarkup
;
907 $validFlags = $this->mConverter
->mFlags
;
909 $tt = explode($markup['flagsep'], $text, 2);
910 if(count($tt) == 2) {
911 $f = explode($markup['varsep'], $tt[0]);
914 if(array_key_exists($ff, $validFlags) &&
915 !in_array($validFlags[$ff], $flags))
916 $flags[] = $validFlags[$ff];
924 if( in_array('R',$flags) ){
925 $flags = array('R');// remove other flags
926 } elseif ( in_array('N',$flags) ){
927 $flags = array('N');// remove other flags
928 } elseif ( in_array('-',$flags) ){
929 $flags = array('-');// remove other flags
930 } elseif (count($flags)==1 && $flags[0]=='T'){
932 } elseif ( in_array('H',$flags) ){
933 // replace A flag, and remove other flags except T
934 $temp=array('+','H');
935 if(in_array('T',$flags)) $temp[] = 'T';
936 if(in_array('D',$flags)) $temp[] = 'D';
939 if ( in_array('A',$flags)) {
943 if ( in_array('D',$flags) )
944 $flags=array_diff($flags,array('S'));
946 if ( count($flags)==0 )
948 $this->mRules
=$rules;
949 $this->mFlags
=$flags;
953 * generate conversion table
956 function parseRules() {
957 $rules = $this->mRules
;
958 $flags = $this->mFlags
;
960 $unidtable = array();
961 $markup = $this->mConverter
->mMarkup
;
963 $choice = explode($markup['varsep'], $rules );
964 foreach($choice as $c) {
965 $v = explode($markup['codesep'], $c);
967 continue;// syntax error, skip
970 $u = explode($markup['unidsep'], $v);
973 } else if(count($u) == 2){
974 $from=trim($u[0]);$v=trim($u[1]);
975 if( array_key_exists($v,$unidtable) && !is_array($unidtable[$v]) )
976 $unidtable[$v]=array($from=>$to);
978 $unidtable[$v][$from]=$to;
980 // syntax error, pass
981 if (!array_key_exists($v,$this->mConverter
->mVariantNames
)){
983 $unidtable = array();
987 $this->mBidtable
= $bidtable;
988 $this->mUnidtable
= $unidtable;
994 function getRulesDesc(){
995 $codesep = $this->mConverter
->mDescCodeSep
;
996 $varsep = $this->mConverter
->mDescVarSep
;
998 foreach($this->mBidtable
as $k => $v)
999 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
1000 foreach($this->mUnidtable
as $k => $a)
1001 foreach($a as $from=>$to)
1002 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
1007 * Parse rules conversion
1010 function getRuleConvertedStr($variant,$doConvert){
1011 $bidtable = $this->mBidtable
;
1012 $unidtable = $this->mUnidtable
;
1014 if( count($bidtable) +
count($unidtable) == 0 ){
1015 return $this->mRules
;
1016 } elseif ($doConvert){// the text converted
1017 // display current variant in bidirectional array
1018 $disp = $this->getTextInBidtable($variant);
1019 // or display current variant in fallbacks
1021 $disp = $this->getTextInBidtable(
1022 $this->mConverter
->getVariantFallbacks($variant));
1023 // or display current variant in unidirectional array
1024 if(!$disp && array_key_exists($variant,$unidtable)){
1025 $disp = array_values($unidtable[$variant]);
1028 // or display frist text under disable manual convert
1029 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
1030 if(count($bidtable)>0){
1031 $disp = array_values($bidtable);
1034 $disp = array_values($unidtable);
1035 $disp = array_values($disp[0]);
1040 } else {// no convert
1041 return $this->mRules
;
1046 * generate conversion table for all text
1049 function generateConvTable(){
1050 $flags = $this->mFlags
;
1051 $bidtable = $this->mBidtable
;
1052 $unidtable = $this->mUnidtable
;
1053 $manLevel = $this->mConverter
->mManualLevel
;
1056 foreach($this->mConverter
->mVariants
as $v) {
1057 /* for bidirectional array
1058 fill in the missing variants, if any,
1060 if(!array_key_exists($v, $bidtable)) {
1061 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
1062 $vf = $this->getTextInBidtable($variantFallbacks);
1063 if($vf) $bidtable[$v] = $vf;
1066 if(array_key_exists($v,$bidtable)){
1067 foreach($vmarked as $vo){
1068 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1069 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1070 // to introduce a custom mapping between
1071 // words WordZh and WordTw in the whole text
1072 if($manLevel[$v]=='bidirectional'){
1073 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1075 if($manLevel[$vo]=='bidirectional'){
1076 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1081 /*for unidirectional array
1082 fill to convert tables */
1083 $allow_unid = $manLevel[$v]=='bidirectional'
1084 ||
$manLevel[$v]=='unidirectional';
1085 if($allow_unid && array_key_exists($v,$unidtable)){
1086 $ct=$this->mConvTable
[$v];
1087 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1093 * Parse rules and flags
1096 function parse($variant){
1097 if(!$variant) $variant = $this->mConverter
->getPreferredVariant();
1099 $this->parseFlags();
1100 $flags = $this->mFlags
;
1102 if( !in_array('R',$flags) ||
!in_array('N',$flags) ){
1103 //FIXME: may cause trouble here...
1104 //strip since it interferes with the parsing, plus,
1105 //all spaces should be stripped in this tag anyway.
1106 $this->mRules
= str_replace(' ', '', $this->mRules
);
1107 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1108 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1110 $this->parseRules();
1112 $rules = $this->mRules
;
1114 if(count($this->mBidtable
)==0 && count($this->mUnidtable
)==0){
1115 if(in_array('+',$flags) ||
in_array('-',$flags))
1116 // fill all variants if text in -{A/H/-|text} without rules
1117 foreach($this->mConverter
->mVariants
as $v)
1118 $this->mBidtable
[$v] = $rules;
1119 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1120 $this->mFlags
= $flags = array('R');
1123 if( in_array('R',$flags) ) {
1124 // if we don't do content convert, still strip the -{}- tags
1125 $this->mRuleDisplay
= $rules;
1126 } elseif ( in_array('N',$flags) ){
1127 // proces N flag: output current variant name
1128 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1129 } elseif ( in_array('D',$flags) ){
1130 // proces D flag: output rules description
1131 $this->mRuleDisplay
= $this->getRulesDesc();
1132 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1133 // proces H,- flag or T only: output nothing
1134 $this->mRuleDisplay
= '';
1135 } elseif ( in_array('S',$flags) ){
1136 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1137 $this->mConverter
->mDoContentConvert
);
1139 $this->mRuleDisplay
= $this->mManualCodeError
;
1142 if ( in_array('T',$flags) ) {
1143 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1144 $this->mConverter
->mDoTitleConvert
);
1147 if (in_array('-', $flags))
1148 $this->mRulesAction
='remove';
1149 if (in_array('+', $flags))
1150 $this->mRulesAction
='add';
1152 $this->generateConvTable();
1158 function hasRules(){
1163 * get display text on markup -{...}-
1166 function getDisplay(){
1167 return $this->mRuleDisplay
;
1170 * get converted title
1173 function getTitle(){
1174 return $this->mRuleTitle
;
1178 * return how deal with conversion rules
1181 function getRulesAction(){
1182 return $this->mRulesAction
;
1186 * get conversion table ( bidirectional and unidirectional conversion table )
1189 function getConvTable(){
1190 return $this->mConvTable
;
1194 * get conversion rules string
1197 function getRules(){
1198 return $this->mRules
;
1202 * get conversion flags
1205 function getFlags(){
1206 return $this->mFlags
;