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 $mNamespaceTables;
27 var $mTitleDisplay='';
28 var $mDoTitleConvert=true, $mDoContentConvert=true;
29 var $mManualLevel; // 'bidirectional' 'unidirectional' 'disable' for each variants
30 var $mTitleFromFlag = false;
35 var $mDescCodeSep = ':',$mDescVarSep = ';';
36 var $mUcfirst = false;
38 const CACHE_VERSION_KEY
= 'VERSION 6';
43 * @param string $maincode the main language code of this language
44 * @param array $variants the supported variants of this language
45 * @param array $variantfallback the fallback language of each variant
46 * @param array $markup array defining the markup used for manual conversion
47 * @param array $flags array defining the custom strings that maps to the flags
48 * @param array $manualLevel limit for supported variants
51 function __construct($langobj, $maincode,
53 $variantfallbacks=array(),
56 $manualLevel = array() ) {
57 $this->mLangObj
= $langobj;
58 $this->mMainLanguageCode
= $maincode;
59 $this->mVariants
= $variants;
60 $this->mVariantFallbacks
= $variantfallbacks;
61 global $wgLanguageNames;
62 $this->mVariantNames
= $wgLanguageNames;
63 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
67 'unidsep'=>'=>', //for unidirectional conversion
72 $this->mMarkup
= array_merge($m, $markup);
74 // 'S' show converted text
75 // '+' add rules for alltext
76 // 'E' the gave flags is error
77 // these flags above are reserved for program
78 'A'=>'A', // add rule for convert code (all text convert)
79 'T'=>'T', // title convert
80 'R'=>'R', // raw content
81 'D'=>'D', // convert description (subclass implement)
82 '-'=>'-', // remove convert (not implement)
83 'H'=>'H', // add rule for convert code (but no display in placed code )
84 'N'=>'N' // current variant name
86 $this->mFlags
= array_merge($f, $flags);
87 foreach( $this->mVariants
as $v) {
88 $this->mManualLevel
[$v]=array_key_exists($v,$manualLevel)
91 $this->mManualAddTables
[$v] = array();
92 $this->mManualRemoveTables
[$v] = array();
93 $this->mNamespaceTables
[$v] = array();
100 function getVariants() {
101 return $this->mVariants
;
105 * in case some variant is not defined in the markup, we need
106 * to have some fallback. for example, in zh, normally people
107 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
108 * when zh-sg is preferred but not defined, we will pick zh-hans
109 * in this case. right now this is only used by zh.
111 * @param string $v the language code of the variant
112 * @return string array the code of the fallback language or false if there is no fallback
115 function getVariantFallbacks($v) {
116 if( isset( $this->mVariantFallbacks
[$v] ) ) {
117 return $this->mVariantFallbacks
[$v];
119 return $this->mMainLanguageCode
;
123 * get preferred language variants.
124 * @param boolean $fromUser Get it from $wgUser's preferences
125 * @return string the preferred language code
128 function getPreferredVariant( $fromUser = true ) {
129 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
131 if($this->mPreferredVariant
)
132 return $this->mPreferredVariant
;
134 // figure out user lang without constructing wgLang to avoid infinite recursion
136 $defaultUserLang = $wgUser->getOption( 'language' );
138 $defaultUserLang = $this->mMainLanguageCode
;
139 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
140 // see if interface language is same as content, if not, prevent conversion
141 if( ! in_array( $userLang, $this->mVariants
) ){
142 $this->mPreferredVariant
= $this->mMainLanguageCode
; // no conversion
143 return $this->mPreferredVariant
;
146 // see if the preference is set in the request
147 $req = $wgRequest->getText( 'variant' );
148 if( in_array( $req, $this->mVariants
) ) {
149 $this->mPreferredVariant
= $req;
153 // check the syntax /code/ArticleTitle
154 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
155 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
156 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
157 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
158 if(in_array($scriptBase,$this->mVariants
)){
159 $this->mPreferredVariant
= $scriptBase;
160 return $this->mPreferredVariant
;
164 // get language variant preference from logged in users
165 // Don't call this on stub objects because that causes infinite
166 // recursion during initialisation
167 if( $fromUser && $wgUser->isLoggedIn() ) {
168 $this->mPreferredVariant
= $wgUser->getOption('variant');
169 return $this->mPreferredVariant
;
172 // see if default variant is globaly set
173 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
174 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
175 return $this->mPreferredVariant
;
178 # FIXME rewrite code for parsing http header. The current code
179 # is written specific for detecting zh- variants
180 if( !$this->mPreferredVariant
) {
181 // see if some supported language variant is set in the
182 // http header, but we don't set the mPreferredVariant
183 // variable in case this is called before the user's
184 // preference is loaded
185 $pv=$this->mMainLanguageCode
;
186 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
187 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
188 $zh = strstr($header, $pv.'-');
190 $ary = split("[,;]",$zh);
194 // don't try to return bad variant
195 if(in_array( $pv, $this->mVariants
))
199 return $this->mMainLanguageCode
;
204 * caption convert, base on preg_replace_callback
206 * to convert text in "title" or "alt", like '<img alt="text" ... '
207 * or '<span title="text" ... '
209 * @return string like ' alt="yyyy"' or ' title="yyyy"'
212 function captionConvert( $matches ) {
213 $toVariant = $this->getPreferredVariant();
214 $title = $matches[1];
216 // we convert captions except URL
217 if( !strpos( $text, '://' ) )
218 $text = $this->translate($text, $toVariant);
219 return " $title=\"$text\"";
223 * dictionary-based conversion
225 * @param string $text the text to be converted
226 * @param string $toVariant the target language code
227 * @return string the converted text
230 function autoConvert($text, $toVariant=false) {
231 $fname="LanguageConverter::autoConvert";
233 wfProfileIn( $fname );
235 if(!$this->mTablesLoaded
)
239 $toVariant = $this->getPreferredVariant();
240 if(!in_array($toVariant, $this->mVariants
))
243 /* we convert everything except:
244 1. html markups (anything between < and >)
246 3. place holders created by the parser
249 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
250 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
254 // this one is needed when the text is inside an html markup
255 $htmlfix = '|<[^>]+$|^[^<>]*>';
257 // disable convert to variants between <code></code> tags
258 $codefix = '<code>.+?<\/code>|';
259 // disable convertsion of <script type="text/javascript"> ... </script>
260 $scriptfix = '<script.*?>.*?<\/script>|';
261 // disable conversion of <pre xxxx> ... </pre>
262 $prefix = '<pre.*?>.*?<\/pre>|';
264 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
266 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
268 $m = array_shift($matches);
270 $ret = $this->translate($m[0], $toVariant);
271 $mstart = $m[1]+
strlen($m[0]);
273 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
274 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
275 foreach($matches as $m) {
276 $mark = substr($text, $mstart, $m[1]-$mstart);
277 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
279 $ret .= $this->translate($m[0], $toVariant);
280 $mstart = $m[1] +
strlen($m[0]);
282 wfProfileOut( $fname );
287 * Translate a string to a variant
288 * Doesn't process markup or do any of that other stuff, for that use convert()
290 * @param string $text Text to convert
291 * @param string $variant Variant language code
292 * @return string Translated text
295 function translate( $text, $variant ) {
296 wfProfileIn( __METHOD__
);
297 if( !$this->mTablesLoaded
)
299 $text = $this->mTables
[$variant]->replace( $text );
300 wfProfileOut( __METHOD__
);
305 * convert text to all supported variants
307 * @param string $text the text to be converted
308 * @return array of string
311 function autoConvertToAllVariants($text) {
312 $fname="LanguageConverter::autoConvertToAllVariants";
313 wfProfileIn( $fname );
314 if( !$this->mTablesLoaded
)
318 foreach($this->mVariants
as $variant) {
319 $ret[$variant] = $this->translate($text, $variant);
322 wfProfileOut( $fname );
327 * convert link text to all supported variants
329 * @param string $text the text to be converted
330 * @return array of string
333 function convertLinkToAllVariants($text) {
334 if( !$this->mTablesLoaded
)
338 $tarray = explode($this->mMarkup
['begin'], $text);
339 $tfirst = array_shift($tarray);
341 foreach($this->mVariants
as $variant)
342 $ret[$variant] = $this->translate($tfirst,$variant);
344 foreach($tarray as $txt) {
345 $marked = explode($this->mMarkup
['end'], $txt, 2);
347 foreach($this->mVariants
as $variant){
348 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
349 if(array_key_exists(1, $marked))
350 $ret[$variant] .= $this->translate($marked[1],$variant);
359 * prepare manual conversion table
362 function prepareManualConv( $convRule ){
363 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
364 $title = $convRule->getTitle();
366 $this->mTitleFromFlag
= true;
367 $this->mTitleDisplay
= $title;
370 //apply manual conversion table to global table
371 $convTable = $convRule->getConvTable();
372 $action = $convRule->getRulesAction();
373 foreach( $convTable as $v => $t ) {
374 if( !in_array( $v, $this->mVariants
) )continue;
375 if( $action=="add" ) {
376 foreach( $t as $from => $to ) {
377 // to ensure that $from and $to not be left blank
378 // so $this->translate() could always return a string
380 // more efficient than array_merge(), about 2.5 times.
381 $this->mManualAddTables
[$v][$from] = $to;
384 elseif ( $action == "remove" ) {
385 foreach ( $t as $from=>$to ) {
387 $this->mManualRemoveTables
[$v][$from] = $to;
394 * apply manual conversion from $this->mManualAddTables and $this->mManualRemoveTables
397 function applyManualConv(){
398 //apply manual conversion table to global table
399 foreach($this->mVariants
as $v) {
400 if (count($this->mManualAddTables
[$v]) > 0) {
401 $this->mTables
[$v]->mergeArray($this->mManualAddTables
[$v]);
403 if (count($this->mManualRemoveTables
[$v]) > 0)
404 $this->mTables
[$v]->removeArray($this->mManualRemoveTables
[$v]);
409 * Convert text using a parser object for context
412 function parserConvert( $text, &$parser ) {
413 global $wgDisableLangConversion;
414 /* don't do anything if this is the conversion table */
415 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
416 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
421 if ( $wgDisableLangConversion )
424 $text = $this->convert( $text );
426 if ( $this->mTitleFromFlag
)
427 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
433 * @param string $title the title included namespace
434 * @return array of string
437 function convertNamespace( $title, $variant ) {
438 $splittitle = explode( ':', $title );
439 if (count($splittitle) < 2)
441 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) )
442 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
443 $ret = implode(':', $splittitle );
451 function convertTitle( $text, $variant ){
452 global $wgDisableTitleConversion, $wgUser;
454 // check for global param and __NOTC__ tag
455 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
$wgUser->getOption('noconvertlink') == 1 ) {
456 $this->mTitleDisplay
= $text;
460 // use the title from the T flag if any
461 if( $this->mTitleFromFlag
){
462 $this->mTitleFromFlag
= false;
463 return $this->mTitleDisplay
;
467 $isredir = $wgRequest->getText( 'redirect', 'yes' );
468 $action = $wgRequest->getText( 'action' );
469 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
470 if ( $isredir == 'no' ||
$action == 'edit' ||
$action == 'submit' ||
$linkconvert == 'no' ) {
473 $text = $this->convertNamespace( $text, $variant );
474 $this->mTitleDisplay
= $this->convert( $text );
475 return $this->mTitleDisplay
;
480 * convert text to different variants of a language. the automatic
481 * conversion is done in autoConvert(). here we parse the text
482 * marked with -{}-, which specifies special conversions of the
483 * text that can not be accomplished in autoConvert()
485 * syntax of the markup:
486 * -{code1:text1;code2:text2;...}- or
487 * -{flags|code1:text1;code2:text2;...}- or
488 * -{text}- in which case no conversion should take place for text
490 * @param string $text text to be converted
491 * @param bool $isTitle whether this conversion is for the article title
492 * @return string converted text
495 function convert( $text, $isTitle = false ) {
497 $mw =& MagicWord
::get( 'notitleconvert' );
498 if( $mw->matchAndRemove( $text ) )
499 $this->mDoTitleConvert
= false;
500 $mw =& MagicWord
::get( 'nocontentconvert' );
501 if( $mw->matchAndRemove( $text ) ) {
502 $this->mDoContentConvert
= false;
505 // no conversion if redirecting
506 $mw =& MagicWord
::get( 'redirect' );
507 if( $mw->matchStart( $text ) )
510 $plang = $this->getPreferredVariant();
512 // for title convertion
513 if ( $isTitle ) return $this->convertTitle( $text, $plang );
515 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
519 foreach ( $tarray as $txt ) {
520 $marked = explode( $this->mMarkup
['begin'], $txt, 2 );
521 if ( array_key_exists( 1, $marked ) ) {
522 $crule = new ConverterRule($marked[1], $this);
523 $crule->parse( $plang );
524 $marked[1] = $crule->getDisplay();
525 $this->prepareManualConv( $crule );
528 $marked[0] .= $this->mMarkup
['end'];
529 array_push( $marks, $marked );
531 $this->applyManualConv();
532 foreach ( $marks as $marked ) {
533 if( $this->mDoContentConvert
)
534 $text .= $this->autoConvert( $marked[0], $plang );
537 if( array_key_exists( 1, $marked ) )
540 // Remove the last delimiter (wasn't real)
541 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
547 * if a language supports multiple variants, it is
548 * possible that non-existing link in one variant
549 * actually exists in another variant. this function
550 * tries to find it. See e.g. LanguageZh.php
552 * @param string $link the name of the link
553 * @param mixed $nt the title object of the link
554 * @param boolean $ignoreOtherCond: to disable other conditions when
555 * we need to transclude a template or update a category's link
556 * @return null the input parameters may be modified upon return
559 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
560 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
561 $isredir = $wgRequest->getText( 'redirect', 'yes' );
562 $action = $wgRequest->getText( 'action' );
563 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
564 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
565 $linkBatch = new LinkBatch();
569 if ( $disableLinkConversion ||
( !$ignoreOtherCond && ( $isredir == 'no' ||
$action == 'edit'
570 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) )
574 $ns = $nt->getNamespace();
576 $variants = $this->autoConvertToAllVariants($link);
577 if($variants == false) //give up
582 foreach( $variants as $v ) {
584 $varnt = Title
::newFromText( $v, $ns );
585 if(!is_null($varnt)){
586 $linkBatch->addObj($varnt);
592 // fetch all variants in single query
593 $linkBatch->execute();
595 foreach( $titles as $varnt ) {
596 if( $varnt->getArticleID() > 0 ) {
598 $link = $varnt->getText();
605 * returns language specific hash options
609 function getExtraHashOptions() {
610 $variant = $this->getPreferredVariant();
611 return '!' . $variant ;
615 * get title text as defined in the body of the article text
619 function getParsedTitle() {
620 return $this->mTitleDisplay
;
624 * a write lock to the cache
628 function lockCache() {
631 for($i=0; $i<30; $i++
) {
632 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
644 function unlockCache() {
646 $wgMemc->delete($this->mCacheKey
. "lock");
651 * Load default conversion tables
652 * This method must be implemented in derived class
656 function loadDefaultTables() {
657 $name = get_class($this);
658 wfDie("Must implement loadDefaultTables() method in class $name");
662 * load conversion tables either from the cache or the disk
665 function loadTables($fromcache=true) {
667 if( $this->mTablesLoaded
)
669 wfProfileIn( __METHOD__
);
670 $this->mTablesLoaded
= true;
671 $this->mTables
= false;
673 wfProfileIn( __METHOD__
.'-cache' );
674 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
675 wfProfileOut( __METHOD__
.'-cache' );
677 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
678 wfProfileIn( __METHOD__
.'-recache' );
679 // not in cache, or we need a fresh reload.
680 // we will first load the default tables
681 // then update them using things in MediaWiki:Zhconversiontable/*
682 $this->loadDefaultTables();
683 foreach($this->mVariants
as $var) {
684 $cached = $this->parseCachedTable($var);
685 $this->mTables
[$var]->mergeArray($cached);
688 $this->postLoadTables();
689 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
691 if($this->lockCache()) {
692 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
693 $this->unlockCache();
695 wfProfileOut( __METHOD__
.'-recache' );
697 wfProfileOut( __METHOD__
);
701 * Hook for post processig after conversion tables are loaded
704 function postLoadTables() {}
707 * Reload the conversion tables
711 function reloadTables() {
713 unset($this->mTables
);
714 $this->mTablesLoaded
= false;
715 $this->loadTables(false);
720 * parse the conversion table stored in the cache
722 * the tables should be in blocks of the following form:
729 * to make the tables more manageable, subpages are allowed
730 * and will be parsed recursively if $recursive=true
733 function parseCachedTable($code, $subpage='', $recursive=true) {
734 global $wgMessageCache;
735 static $parsed = array();
737 if(!is_object($wgMessageCache))
740 $key = 'Conversiontable/'.$code;
742 $key .= '/' . $subpage;
744 if(array_key_exists($key, $parsed))
747 if ( strpos( $code, '/' ) === false ) {
748 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
750 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
751 if ( $title && $title->exists() ) {
752 $article = new Article( $title );
753 $txt = $article->getContents();
759 // get all subpage links of the form
760 // [[MediaWiki:conversiontable/zh-xx/...|...]]
761 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
762 $subs = explode('[[', $txt);
764 foreach( $subs as $sub ) {
765 $link = explode(']]', $sub, 2);
766 if(count($link) != 2)
768 $b = explode('|', $link[0]);
769 $b = explode('/', trim($b[0]), 3);
775 if($b[0] == $linkhead && $b[1] == $code) {
776 $sublinks[] = $sublink;
781 // parse the mappings in this page
782 $blocks = explode($this->mMarkup
['begin'], $txt);
783 array_shift($blocks);
785 foreach($blocks as $block) {
786 $mappings = explode($this->mMarkup
['end'], $block, 2);
787 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
788 $table = explode( ';', $stripped );
789 foreach( $table as $t ) {
790 $m = explode( '=>', $t );
791 if( count( $m ) != 2)
793 // trim any trailling comments starting with '//'
794 $tt = explode('//', $m[1], 2);
795 $ret[trim($m[0])] = trim($tt[0]);
798 $parsed[$key] = true;
801 // recursively parse the subpages
803 foreach($sublinks as $link) {
804 $s = $this->parseCachedTable($code, $link, $recursive);
805 $ret = array_merge($ret, $s);
809 if ($this->mUcfirst
) {
810 foreach ($ret as $k => $v) {
811 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
818 * Enclose a string with the "no conversion" tag. This is used by
819 * various functions in the Parser
821 * @param string $text text to be tagged for no conversion
822 * @return string the tagged text
825 function markNoConversion($text, $noParse=false) {
826 # don't mark if already marked
827 if(strpos($text, $this->mMarkup
['begin']) ||
828 strpos($text, $this->mMarkup
['end']))
831 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
836 * convert the sorting key for category links. this should make different
837 * keys that are variants of each other map to the same key
839 function convertCategoryKey( $key ) {
843 * hook to refresh the cache of conversion tables when
844 * MediaWiki:conversiontable* is updated
847 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
848 $titleobj = $article->getTitle();
849 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
850 $title = $titleobj->getDBkey();
851 $t = explode('/', $title, 3);
853 if( $c > 1 && $t[0] == 'Conversiontable' ) {
854 if(in_array($t[1], $this->mVariants
)) {
855 $this->reloadTables();
863 * Armour rendered math against conversion
864 * Wrap math into rawoutput -{R| math }- syntax
867 function armourMath($text){
868 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
874 * parser for rules of language conversion , parse rules in -{ }- tag
876 * @author fdcn <fdcn64@gmail.com>
878 class ConverterRule
{
879 var $mText; // original text in -{text}-
880 var $mConverter; // LanguageConverter object
881 var $mManualCodeError='<strong class="error">code error!</strong>';
882 var $mRuleDisplay = '',$mRuleTitle=false;
883 var $mRules = '';// string : the text of the rules
884 var $mRulesAction = 'none';
885 var $mFlags = array();
886 var $mConvTable = array();
887 var $mBidtable = array();// array of the translation in each variant
888 var $mUnidtable = array();// array of the translation in each variant
893 * @param string $text the text between -{ and }-
894 * @param object $converter a LanguageConverter object
897 function __construct($text,$converter){
898 $this->mText
= $text;
899 $this->mConverter
=$converter;
900 foreach($converter->mVariants
as $v){
901 $this->mConvTable
[$v]=array();
906 * check if variants array in convert array
908 * @param string $variant Variant language code
909 * @return string Translated text
912 function getTextInBidtable($variants){
913 if(is_string($variants)){ $variants=array($variants); }
914 if(!is_array($variants)) return false;
915 foreach ($variants as $variant){
916 if(array_key_exists($variant, $this->mBidtable
)){
917 return $this->mBidtable
[$variant];
924 * Parse flags with syntax -{FLAG| ... }-
927 function parseFlags(){
928 $text = $this->mText
;
929 if(strlen($text) < 2 ) {
930 $this->mFlags
= array( 'R' );
931 $this->mRules
= $text;
936 $markup = $this->mConverter
->mMarkup
;
937 $validFlags = $this->mConverter
->mFlags
;
939 $tt = explode($markup['flagsep'], $text, 2);
940 if(count($tt) == 2) {
941 $f = explode($markup['varsep'], $tt[0]);
944 if(array_key_exists($ff, $validFlags) &&
945 !in_array($validFlags[$ff], $flags))
946 $flags[] = $validFlags[$ff];
954 if( in_array('R',$flags) ){
955 $flags = array('R');// remove other flags
956 } elseif ( in_array('N',$flags) ){
957 $flags = array('N');// remove other flags
958 } elseif ( in_array('-',$flags) ){
959 $flags = array('-');// remove other flags
960 } elseif (count($flags)==1 && $flags[0]=='T'){
962 } elseif ( in_array('H',$flags) ){
963 // replace A flag, and remove other flags except T
964 $temp=array('+','H');
965 if(in_array('T',$flags)) $temp[] = 'T';
966 if(in_array('D',$flags)) $temp[] = 'D';
969 if ( in_array('A',$flags)) {
973 if ( in_array('D',$flags) )
974 $flags=array_diff($flags,array('S'));
976 if ( count($flags)==0 )
978 $this->mRules
=$rules;
979 $this->mFlags
=$flags;
983 * generate conversion table
986 function parseRules() {
987 $rules = $this->mRules
;
988 $flags = $this->mFlags
;
990 $unidtable = array();
991 $markup = $this->mConverter
->mMarkup
;
993 $choice = explode($markup['varsep'], $rules );
994 foreach($choice as $c) {
995 $v = explode($markup['codesep'], $c);
997 continue;// syntax error, skip
1000 $u = explode($markup['unidsep'], $v);
1001 if(count($u) == 1) {
1002 $bidtable[$v] = $to;
1003 } else if(count($u) == 2){
1004 $from=trim($u[0]);$v=trim($u[1]);
1005 if( array_key_exists($v,$unidtable) && !is_array($unidtable[$v]) )
1006 $unidtable[$v]=array($from=>$to);
1008 $unidtable[$v][$from]=$to;
1010 // syntax error, pass
1011 if (!array_key_exists($v,$this->mConverter
->mVariantNames
)){
1012 $bidtable = array();
1013 $unidtable = array();
1017 $this->mBidtable
= $bidtable;
1018 $this->mUnidtable
= $unidtable;
1024 function getRulesDesc(){
1025 $codesep = $this->mConverter
->mDescCodeSep
;
1026 $varsep = $this->mConverter
->mDescVarSep
;
1028 foreach($this->mBidtable
as $k => $v)
1029 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
1030 foreach($this->mUnidtable
as $k => $a)
1031 foreach($a as $from=>$to)
1032 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
1037 * Parse rules conversion
1040 function getRuleConvertedStr($variant,$doConvert){
1041 $bidtable = $this->mBidtable
;
1042 $unidtable = $this->mUnidtable
;
1044 if( count($bidtable) +
count($unidtable) == 0 ){
1045 return $this->mRules
;
1046 } elseif ($doConvert){// the text converted
1047 // display current variant in bidirectional array
1048 $disp = $this->getTextInBidtable($variant);
1049 // or display current variant in fallbacks
1051 $disp = $this->getTextInBidtable(
1052 $this->mConverter
->getVariantFallbacks($variant));
1053 // or display current variant in unidirectional array
1054 if(!$disp && array_key_exists($variant,$unidtable)){
1055 $disp = array_values($unidtable[$variant]);
1058 // or display frist text under disable manual convert
1059 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
1060 if(count($bidtable)>0){
1061 $disp = array_values($bidtable);
1064 $disp = array_values($unidtable);
1065 $disp = array_values($disp[0]);
1070 } else {// no convert
1071 return $this->mRules
;
1076 * generate conversion table for all text
1079 function generateConvTable(){
1080 $flags = $this->mFlags
;
1081 $bidtable = $this->mBidtable
;
1082 $unidtable = $this->mUnidtable
;
1083 $manLevel = $this->mConverter
->mManualLevel
;
1086 foreach($this->mConverter
->mVariants
as $v) {
1087 /* for bidirectional array
1088 fill in the missing variants, if any,
1090 if(!array_key_exists($v, $bidtable)) {
1091 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
1092 $vf = $this->getTextInBidtable($variantFallbacks);
1093 if($vf) $bidtable[$v] = $vf;
1096 if(array_key_exists($v,$bidtable)){
1097 foreach($vmarked as $vo){
1098 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1099 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1100 // to introduce a custom mapping between
1101 // words WordZh and WordTw in the whole text
1102 if($manLevel[$v]=='bidirectional'){
1103 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1105 if($manLevel[$vo]=='bidirectional'){
1106 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1111 /*for unidirectional array
1112 fill to convert tables */
1113 $allow_unid = $manLevel[$v]=='bidirectional'
1114 ||
$manLevel[$v]=='unidirectional';
1115 if($allow_unid && array_key_exists($v,$unidtable)){
1116 $ct=$this->mConvTable
[$v];
1117 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1123 * Parse rules and flags
1126 function parse($variant){
1127 if(!$variant) $variant = $this->mConverter
->getPreferredVariant();
1129 $this->parseFlags();
1130 $flags = $this->mFlags
;
1132 if( !in_array('R',$flags) ||
!in_array('N',$flags) ){
1133 //FIXME: may cause trouble here...
1134 //strip since it interferes with the parsing, plus,
1135 //all spaces should be stripped in this tag anyway.
1136 $this->mRules
= str_replace(' ', '', $this->mRules
);
1137 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1138 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1140 $this->parseRules();
1142 $rules = $this->mRules
;
1144 if(count($this->mBidtable
)==0 && count($this->mUnidtable
)==0){
1145 if(in_array('+',$flags) ||
in_array('-',$flags))
1146 // fill all variants if text in -{A/H/-|text} without rules
1147 foreach($this->mConverter
->mVariants
as $v)
1148 $this->mBidtable
[$v] = $rules;
1149 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1150 $this->mFlags
= $flags = array('R');
1153 if( in_array('R',$flags) ) {
1154 // if we don't do content convert, still strip the -{}- tags
1155 $this->mRuleDisplay
= $rules;
1156 } elseif ( in_array('N',$flags) ){
1157 // proces N flag: output current variant name
1158 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1159 } elseif ( in_array('D',$flags) ){
1160 // proces D flag: output rules description
1161 $this->mRuleDisplay
= $this->getRulesDesc();
1162 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1163 // proces H,- flag or T only: output nothing
1164 $this->mRuleDisplay
= '';
1165 } elseif ( in_array('S',$flags) ){
1166 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1167 $this->mConverter
->mDoContentConvert
);
1169 $this->mRuleDisplay
= $this->mManualCodeError
;
1172 if ( in_array('T',$flags) ) {
1173 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1174 $this->mConverter
->mDoTitleConvert
);
1177 if (in_array('-', $flags))
1178 $this->mRulesAction
='remove';
1179 if (in_array('+', $flags))
1180 $this->mRulesAction
='add';
1182 $this->generateConvTable();
1188 function hasRules(){
1193 * get display text on markup -{...}-
1196 function getDisplay(){
1197 return $this->mRuleDisplay
;
1200 * get converted title
1203 function getTitle(){
1204 return $this->mRuleTitle
;
1208 * return how deal with conversion rules
1211 function getRulesAction(){
1212 return $this->mRulesAction
;
1216 * get conversion table ( bidirectional and unidirectional conversion table )
1219 function getConvTable(){
1220 return $this->mConvTable
;
1224 * get conversion rules string
1227 function getRules(){
1228 return $this->mRules
;
1232 * get conversion flags
1235 function getFlags(){
1236 return $this->mFlags
;