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 $mNamespaceTables;
25 var $mTitleDisplay='';
26 var $mDoTitleConvert=true, $mDoContentConvert=true;
27 var $mManualLevel; // 'bidirectional' 'unidirectional' 'disable' for each variants
28 var $mTitleFromFlag = false;
33 var $mDescCodeSep = ':',$mDescVarSep = ';';
34 var $mUcfirst = false;
36 const CACHE_VERSION_KEY
= 'VERSION 6';
41 * @param string $maincode the main language code of this language
42 * @param array $variants the supported variants of this language
43 * @param array $variantfallback the fallback language of each variant
44 * @param array $markup array defining the markup used for manual conversion
45 * @param array $flags array defining the custom strings that maps to the flags
46 * @param array $manualLevel limit for supported variants
49 function __construct($langobj, $maincode,
51 $variantfallbacks=array(),
54 $manualLevel = array() ) {
55 $this->mLangObj
= $langobj;
56 $this->mMainLanguageCode
= $maincode;
57 $this->mVariants
= $variants;
58 $this->mVariantFallbacks
= $variantfallbacks;
59 global $wgLanguageNames;
60 $this->mVariantNames
= $wgLanguageNames;
61 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
65 'unidsep'=>'=>', //for unidirectional conversion
70 $this->mMarkup
= array_merge($m, $markup);
72 // 'S' show converted text
73 // '+' add rules for alltext
74 // 'E' the gave flags is error
75 // these flags above are reserved for program
76 'A'=>'A', // add rule for convert code (all text convert)
77 'T'=>'T', // title convert
78 'R'=>'R', // raw content
79 'D'=>'D', // convert description (subclass implement)
80 '-'=>'-', // remove convert (not implement)
81 'H'=>'H', // add rule for convert code (but no display in placed code )
82 'N'=>'N' // current variant name
84 $this->mFlags
= array_merge($f, $flags);
85 foreach( $this->mVariants
as $v) {
86 $this->mManualLevel
[$v]=array_key_exists($v,$manualLevel)
89 $this->mNamespaceTables
[$v] = array();
90 $this->mFlags
[$v] = $v;
97 function getVariants() {
98 return $this->mVariants
;
102 * in case some variant is not defined in the markup, we need
103 * to have some fallback. for example, in zh, normally people
104 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
105 * when zh-sg is preferred but not defined, we will pick zh-hans
106 * in this case. right now this is only used by zh.
108 * @param string $v the language code of the variant
109 * @return string array the code of the fallback language or false if there is no fallback
112 function getVariantFallbacks($v) {
113 if( isset( $this->mVariantFallbacks
[$v] ) ) {
114 return $this->mVariantFallbacks
[$v];
116 return $this->mMainLanguageCode
;
120 * get preferred language variants.
121 * @param boolean $fromUser Get it from $wgUser's preferences
122 * @return string the preferred language code
125 function getPreferredVariant( $fromUser = true ) {
126 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
128 if($this->mPreferredVariant
)
129 return $this->mPreferredVariant
;
131 // figure out user lang without constructing wgLang to avoid infinite recursion
133 $defaultUserLang = $wgUser->getOption( 'language' );
135 $defaultUserLang = $this->mMainLanguageCode
;
136 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
137 // see if interface language is same as content, if not, prevent conversion
138 if( ! in_array( $userLang, $this->mVariants
) ){
139 $this->mPreferredVariant
= $this->mMainLanguageCode
; // no conversion
140 return $this->mPreferredVariant
;
143 // see if the preference is set in the request
144 $req = $wgRequest->getText( 'variant' );
145 if( in_array( $req, $this->mVariants
) ) {
146 $this->mPreferredVariant
= $req;
150 // check the syntax /code/ArticleTitle
151 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
152 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
153 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
154 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
155 if(in_array($scriptBase,$this->mVariants
)){
156 $this->mPreferredVariant
= $scriptBase;
157 return $this->mPreferredVariant
;
161 // get language variant preference from logged in users
162 // Don't call this on stub objects because that causes infinite
163 // recursion during initialisation
164 if( $fromUser && $wgUser->isLoggedIn() ) {
165 $this->mPreferredVariant
= $wgUser->getOption('variant');
166 return $this->mPreferredVariant
;
169 // see if default variant is globaly set
170 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
171 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
172 return $this->mPreferredVariant
;
175 if( !$this->mPreferredVariant
) {
176 // see if some supported language variant is set in the
177 // http header, but we don't set the mPreferredVariant
178 // variable in case this is called before the user's
179 // preference is loaded
180 if( array_key_exists( 'HTTP_ACCEPT_LANGUAGE', $_SERVER ) ) {
181 $acceptLanguage = strtolower( $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
184 $result = explode(',', $acceptLanguage);
186 $languages = array();
188 foreach( $result as $elem ) {
189 // if $elem likes 'zh-cn;q=0.9'
190 if(($posi = strpos( $elem, ';' )) !== false ) {
191 // get the real language code likes 'zh-cn'
192 $languages[] = substr( $elem, 0, $posi );
195 $languages[] = $elem;
199 foreach( $languages as $language ) {
201 $language = trim( $language );
202 if( in_array( $language, $this->mVariants
) ) {
210 return $this->mMainLanguageCode
;
215 * caption convert, base on preg_replace_callback
217 * to convert text in "title" or "alt", like '<img alt="text" ... '
218 * or '<span title="text" ... '
220 * @return string like ' alt="yyyy"' or ' title="yyyy"'
223 function captionConvert( $matches ) {
224 $toVariant = $this->getPreferredVariant();
225 $title = $matches[1];
227 // we convert captions except URL
228 if( !strpos( $text, '://' ) )
229 $text = $this->translate($text, $toVariant);
230 return " $title=\"$text\"";
234 * dictionary-based conversion
236 * @param string $text the text to be converted
237 * @param string $toVariant the target language code
238 * @return string the converted text
241 function autoConvert($text, $toVariant=false) {
242 $fname="LanguageConverter::autoConvert";
244 wfProfileIn( $fname );
246 if(!$this->mTablesLoaded
)
250 $toVariant = $this->getPreferredVariant();
251 if(!in_array($toVariant, $this->mVariants
))
254 /* we convert everything except:
255 1. html markups (anything between < and >)
257 3. place holders created by the parser
260 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
261 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
265 // this one is needed when the text is inside an html markup
266 $htmlfix = '|<[^>]+$|^[^<>]*>';
268 // disable convert to variants between <code></code> tags
269 $codefix = '<code>.+?<\/code>|';
270 // disable convertsion of <script type="text/javascript"> ... </script>
271 $scriptfix = '<script.*?>.*?<\/script>|';
272 // disable conversion of <pre xxxx> ... </pre>
273 $prefix = '<pre.*?>.*?<\/pre>|';
275 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
277 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
279 $m = array_shift($matches);
281 $ret = $this->translate($m[0], $toVariant);
282 $mstart = $m[1]+
strlen($m[0]);
284 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
285 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
286 foreach($matches as $m) {
287 $mark = substr($text, $mstart, $m[1]-$mstart);
288 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
290 $ret .= $this->translate($m[0], $toVariant);
291 $mstart = $m[1] +
strlen($m[0]);
293 wfProfileOut( $fname );
298 * Translate a string to a variant
299 * Doesn't process markup or do any of that other stuff, for that use convert()
301 * @param string $text Text to convert
302 * @param string $variant Variant language code
303 * @return string Translated text
306 function translate( $text, $variant ) {
307 wfProfileIn( __METHOD__
);
308 if( !$this->mTablesLoaded
)
310 $text = $this->mTables
[$variant]->replace( $text );
311 wfProfileOut( __METHOD__
);
316 * convert text to all supported variants
318 * @param string $text the text to be converted
319 * @return array of string
322 function autoConvertToAllVariants($text) {
323 $fname="LanguageConverter::autoConvertToAllVariants";
324 wfProfileIn( $fname );
325 if( !$this->mTablesLoaded
)
329 foreach($this->mVariants
as $variant) {
330 $ret[$variant] = $this->translate($text, $variant);
333 wfProfileOut( $fname );
338 * convert link text to all supported variants
340 * @param string $text the text to be converted
341 * @return array of string
344 function convertLinkToAllVariants($text) {
345 if( !$this->mTablesLoaded
)
349 $tarray = explode($this->mMarkup
['begin'], $text);
350 $tfirst = array_shift($tarray);
352 foreach($this->mVariants
as $variant)
353 $ret[$variant] = $this->translate($tfirst,$variant);
355 foreach($tarray as $txt) {
356 $marked = explode($this->mMarkup
['end'], $txt, 2);
358 foreach($this->mVariants
as $variant){
359 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
360 if(array_key_exists(1, $marked))
361 $ret[$variant] .= $this->translate($marked[1],$variant);
370 * prepare manual conversion table
373 function applyManualConv( $convRule ){
374 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
375 $title = $convRule->getTitle();
377 $this->mTitleFromFlag
= true;
378 $this->mTitleDisplay
= $title;
381 //apply manual conversion table to global table
382 $convTable = $convRule->getConvTable();
383 $action = $convRule->getRulesAction();
384 foreach( $convTable as $variant => $pair ) {
385 if( !in_array( $variant, $this->mVariants
) )continue;
386 if( $action=="add" ) {
387 foreach( $pair as $from => $to ) {
388 // to ensure that $from and $to not be left blank
389 // so $this->translate() could always return a string
391 // more efficient than array_merge(), about 2.5 times.
392 $this->mTables
[$variant]->setPair( $from, $to );
395 elseif ( $action == "remove" ) {
396 $this->mTables
[$variant]->removeArray( $pair );
402 * Convert text using a parser object for context
405 function parserConvert( $text, &$parser ) {
406 global $wgDisableLangConversion;
407 /* don't do anything if this is the conversion table */
408 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
409 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
414 if ( $wgDisableLangConversion )
417 $text = $this->convert( $text );
419 if ( $this->mTitleFromFlag
)
420 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
426 * @param string $title the title included namespace
427 * @return array of string
430 function convertNamespace( $title, $variant ) {
431 $splittitle = explode( ':', $title );
432 if (count($splittitle) < 2)
434 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) )
435 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
436 $ret = implode(':', $splittitle );
444 function convertTitle( $text, $variant ){
445 global $wgDisableTitleConversion, $wgUser;
447 // check for global param and __NOTC__ tag
448 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
$wgUser->getOption('noconvertlink') == 1 ) {
449 $this->mTitleDisplay
= $text;
453 // use the title from the T flag if any
454 if( $this->mTitleFromFlag
){
455 $this->mTitleFromFlag
= false;
456 return $this->mTitleDisplay
;
460 $isredir = $wgRequest->getText( 'redirect', 'yes' );
461 $action = $wgRequest->getText( 'action' );
462 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
463 if ( $isredir == 'no' ||
$action == 'edit' ||
$action == 'submit' ||
$linkconvert == 'no' ) {
466 $text = $this->convertNamespace( $text, $variant );
467 $this->mTitleDisplay
= $this->convert( $text );
468 return $this->mTitleDisplay
;
473 * convert text to different variants of a language. the automatic
474 * conversion is done in autoConvert(). here we parse the text
475 * marked with -{}-, which specifies special conversions of the
476 * text that can not be accomplished in autoConvert()
478 * syntax of the markup:
479 * -{code1:text1;code2:text2;...}- or
480 * -{flags|code1:text1;code2:text2;...}- or
481 * -{text}- in which case no conversion should take place for text
483 * @param string $text text to be converted
484 * @param bool $isTitle whether this conversion is for the article title
485 * @return string converted text
488 function convert( $text, $isTitle = false ) {
490 $mw =& MagicWord
::get( 'notitleconvert' );
491 if( $mw->matchAndRemove( $text ) )
492 $this->mDoTitleConvert
= false;
493 $mw =& MagicWord
::get( 'nocontentconvert' );
494 if( $mw->matchAndRemove( $text ) ) {
495 $this->mDoContentConvert
= false;
498 // no conversion if redirecting
499 $mw =& MagicWord
::get( 'redirect' );
500 if( $mw->matchStart( $text ) )
503 $plang = $this->getPreferredVariant();
505 // for title convertion
506 if ( $isTitle ) return $this->convertTitle( $text, $plang );
508 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
511 foreach ( $tarray as $txt ) {
513 $marked = explode( $this->mMarkup
['begin'], $txt, 2 );
515 if( $this->mDoContentConvert
)
516 // Bug 19620: should convert a string immediately after a new rule added.
517 $text .= $this->autoConvert( $marked[0], $plang );
519 if ( array_key_exists( 1, $marked ) ) {
520 $crule = new ConverterRule($marked[1], $this);
521 $crule->parse( $plang );
522 $text .= $crule->getDisplay();
523 $this->applyManualConv( $crule );
526 $text .= $this->mMarkup
['end'];
530 // Remove the last delimiter (wasn't real)
531 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
537 * if a language supports multiple variants, it is
538 * possible that non-existing link in one variant
539 * actually exists in another variant. this function
540 * tries to find it. See e.g. LanguageZh.php
542 * @param string $link the name of the link
543 * @param mixed $nt the title object of the link
544 * @param boolean $ignoreOtherCond: to disable other conditions when
545 * we need to transclude a template or update a category's link
546 * @return null the input parameters may be modified upon return
549 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
550 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
551 $isredir = $wgRequest->getText( 'redirect', 'yes' );
552 $action = $wgRequest->getText( 'action' );
553 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
554 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
555 $linkBatch = new LinkBatch();
559 if ( $disableLinkConversion ||
( !$ignoreOtherCond && ( $isredir == 'no' ||
$action == 'edit'
560 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) )
564 $ns = $nt->getNamespace();
566 $variants = $this->autoConvertToAllVariants($link);
567 if($variants == false) //give up
572 foreach( $variants as $v ) {
574 $varnt = Title
::newFromText( $v, $ns );
575 if(!is_null($varnt)){
576 $linkBatch->addObj($varnt);
582 // fetch all variants in single query
583 $linkBatch->execute();
585 foreach( $titles as $varnt ) {
586 if( $varnt->getArticleID() > 0 ) {
588 $link = $varnt->getText();
595 * returns language specific hash options
599 function getExtraHashOptions() {
600 $variant = $this->getPreferredVariant();
601 return '!' . $variant ;
605 * get title text as defined in the body of the article text
609 function getParsedTitle() {
610 return $this->mTitleDisplay
;
614 * a write lock to the cache
618 function lockCache() {
621 for($i=0; $i<30; $i++
) {
622 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
634 function unlockCache() {
636 $wgMemc->delete($this->mCacheKey
. "lock");
641 * Load default conversion tables
642 * This method must be implemented in derived class
646 function loadDefaultTables() {
647 $name = get_class($this);
648 wfDie("Must implement loadDefaultTables() method in class $name");
652 * load conversion tables either from the cache or the disk
655 function loadTables($fromcache=true) {
657 if( $this->mTablesLoaded
)
659 wfProfileIn( __METHOD__
);
660 $this->mTablesLoaded
= true;
661 $this->mTables
= false;
663 wfProfileIn( __METHOD__
.'-cache' );
664 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
665 wfProfileOut( __METHOD__
.'-cache' );
667 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
668 wfProfileIn( __METHOD__
.'-recache' );
669 // not in cache, or we need a fresh reload.
670 // we will first load the default tables
671 // then update them using things in MediaWiki:Zhconversiontable/*
672 $this->loadDefaultTables();
673 foreach($this->mVariants
as $var) {
674 $cached = $this->parseCachedTable($var);
675 $this->mTables
[$var]->mergeArray($cached);
678 $this->postLoadTables();
679 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
681 if($this->lockCache()) {
682 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
683 $this->unlockCache();
685 wfProfileOut( __METHOD__
.'-recache' );
687 wfProfileOut( __METHOD__
);
691 * Hook for post processig after conversion tables are loaded
694 function postLoadTables() {}
697 * Reload the conversion tables
701 function reloadTables() {
703 unset($this->mTables
);
704 $this->mTablesLoaded
= false;
705 $this->loadTables(false);
710 * parse the conversion table stored in the cache
712 * the tables should be in blocks of the following form:
719 * to make the tables more manageable, subpages are allowed
720 * and will be parsed recursively if $recursive=true
723 function parseCachedTable($code, $subpage='', $recursive=true) {
724 global $wgMessageCache;
725 static $parsed = array();
727 if(!is_object($wgMessageCache))
730 $key = 'Conversiontable/'.$code;
732 $key .= '/' . $subpage;
734 if(array_key_exists($key, $parsed))
737 if ( strpos( $code, '/' ) === false ) {
738 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
740 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
741 if ( $title && $title->exists() ) {
742 $article = new Article( $title );
743 $txt = $article->getContents();
749 // get all subpage links of the form
750 // [[MediaWiki:conversiontable/zh-xx/...|...]]
751 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
752 $subs = explode('[[', $txt);
754 foreach( $subs as $sub ) {
755 $link = explode(']]', $sub, 2);
756 if(count($link) != 2)
758 $b = explode('|', $link[0]);
759 $b = explode('/', trim($b[0]), 3);
765 if($b[0] == $linkhead && $b[1] == $code) {
766 $sublinks[] = $sublink;
771 // parse the mappings in this page
772 $blocks = explode($this->mMarkup
['begin'], $txt);
773 array_shift($blocks);
775 foreach($blocks as $block) {
776 $mappings = explode($this->mMarkup
['end'], $block, 2);
777 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
778 $table = explode( ';', $stripped );
779 foreach( $table as $t ) {
780 $m = explode( '=>', $t );
781 if( count( $m ) != 2)
783 // trim any trailling comments starting with '//'
784 $tt = explode('//', $m[1], 2);
785 $ret[trim($m[0])] = trim($tt[0]);
788 $parsed[$key] = true;
791 // recursively parse the subpages
793 foreach($sublinks as $link) {
794 $s = $this->parseCachedTable($code, $link, $recursive);
795 $ret = array_merge($ret, $s);
799 if ($this->mUcfirst
) {
800 foreach ($ret as $k => $v) {
801 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
808 * Enclose a string with the "no conversion" tag. This is used by
809 * various functions in the Parser
811 * @param string $text text to be tagged for no conversion
812 * @return string the tagged text
815 function markNoConversion($text, $noParse=false) {
816 # don't mark if already marked
817 if(strpos($text, $this->mMarkup
['begin']) ||
818 strpos($text, $this->mMarkup
['end']))
821 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
826 * convert the sorting key for category links. this should make different
827 * keys that are variants of each other map to the same key
829 function convertCategoryKey( $key ) {
833 * hook to refresh the cache of conversion tables when
834 * MediaWiki:conversiontable* is updated
837 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
838 $titleobj = $article->getTitle();
839 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
840 $title = $titleobj->getDBkey();
841 $t = explode('/', $title, 3);
843 if( $c > 1 && $t[0] == 'Conversiontable' ) {
844 if(in_array($t[1], $this->mVariants
)) {
845 $this->reloadTables();
853 * Armour rendered math against conversion
854 * Wrap math into rawoutput -{R| math }- syntax
857 function armourMath($text){
858 // we need to convert '-{' and '}-' to '-{' and '}-'
859 // to avoid a unwanted '}-' appeared after the math-image.
860 $text = strtr( $text, array('-{' => '-{', '}-' => '}-') );
861 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
867 * parser for rules of language conversion , parse rules in -{ }- tag
869 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
871 class ConverterRule
{
872 var $mText; // original text in -{text}-
873 var $mConverter; // LanguageConverter object
874 var $mManualCodeError='<strong class="error">code error!</strong>';
875 var $mRuleDisplay = '',$mRuleTitle=false;
876 var $mRules = '';// string : the text of the rules
877 var $mRulesAction = 'none';
878 var $mFlags = array();
879 var $mConvTable = array();
880 var $mBidtable = array();// array of the translation in each variant
881 var $mUnidtable = array();// array of the translation in each variant
886 * @param string $text the text between -{ and }-
887 * @param object $converter a LanguageConverter object
890 function __construct($text,$converter){
891 $this->mText
= $text;
892 $this->mConverter
=$converter;
893 foreach($converter->mVariants
as $v){
894 $this->mConvTable
[$v]=array();
899 * check if variants array in convert array
901 * @param string $variant Variant language code
902 * @return string Translated text
905 function getTextInBidtable($variants){
906 if(is_string($variants)){ $variants=array($variants); }
907 if(!is_array($variants)) return false;
908 foreach ($variants as $variant){
909 if(array_key_exists($variant, $this->mBidtable
)){
910 return $this->mBidtable
[$variant];
917 * Parse flags with syntax -{FLAG| ... }-
920 function parseFlags(){
921 $text = $this->mText
;
922 if(strlen($text) < 2 ) {
923 $this->mFlags
= array( 'R' );
924 $this->mRules
= $text;
929 $markup = $this->mConverter
->mMarkup
;
930 $validFlags = $this->mConverter
->mFlags
;
931 $variants = $this->mConverter
->mVariants
;
933 $tt = explode($markup['flagsep'], $text, 2);
934 if(count($tt) == 2) {
935 $f = explode($markup['varsep'], $tt[0]);
938 if(array_key_exists($ff, $validFlags) &&
939 !in_array($validFlags[$ff], $flags))
940 $flags[] = $validFlags[$ff];
948 if( in_array('R',$flags) ){
949 $flags = array('R');// remove other flags
950 } elseif ( in_array('N',$flags) ){
951 $flags = array('N');// remove other flags
952 } elseif ( in_array('-',$flags) ){
953 $flags = array('-');// remove other flags
954 } elseif (count($flags)==1 && $flags[0]=='T'){
956 } elseif ( in_array('H',$flags) ){
957 // replace A flag, and remove other flags except T
958 $temp=array('+','H');
959 if(in_array('T',$flags)) $temp[] = 'T';
960 if(in_array('D',$flags)) $temp[] = 'D';
963 if ( in_array('A',$flags) ) {
967 if ( in_array('D',$flags) )
968 $flags=array_diff($flags,array('S'));
969 $flags_temp = array();
970 foreach ($variants as $variant) {
971 // try to find flags like "zh-hans", "zh-hant"
972 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
973 if ( in_array($variant, $flags) )
974 $flags_temp[] = $variant;
976 if ( count($flags_temp) !== 0 )
977 $flags = $flags_temp;
979 if ( count($flags) == 0 )
981 $this->mRules
=$rules;
982 $this->mFlags
=$flags;
986 * generate conversion table
989 function parseRules() {
990 $rules = $this->mRules
;
991 $flags = $this->mFlags
;
993 $unidtable = array();
994 $markup = $this->mConverter
->mMarkup
;
995 $variants = $this->mConverter
->mVariants
;
997 // varsep_pattern for preg_split:
998 // text should be splited by ";" only if a valid variant
999 // name exist after the markup, for example:
1000 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
1001 // we should split it as:
1003 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1004 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1007 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1008 foreach( $variants as $variant ) {
1009 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
1010 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1011 . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1013 $varsep_pattern .= '\s*$)/';
1015 $choice = preg_split($varsep_pattern, $rules);
1017 foreach( $choice as $c ) {
1018 $v = explode($markup['codesep'], $c, 2);
1019 if( count($v) != 2 )
1020 continue;// syntax error, skip
1023 $u = explode($markup['unidsep'], $v);
1024 // if $to is empty, strtr() could return a wrong result
1025 if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
1026 $bidtable[$v] = $to;
1027 } else if(count($u) == 2){
1028 $from = trim($u[0]);
1030 if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
1031 && $to && in_array( $v, $variants ) )
1032 $unidtable[$v] = array( $from=>$to );
1033 elseif ( $to && in_array( $v, $variants ) )
1034 $unidtable[$v][$from] = $to;
1036 // syntax error, pass
1037 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ){
1038 $bidtable = array();
1039 $unidtable = array();
1043 $this->mBidtable
= $bidtable;
1044 $this->mUnidtable
= $unidtable;
1050 function getRulesDesc(){
1051 $codesep = $this->mConverter
->mDescCodeSep
;
1052 $varsep = $this->mConverter
->mDescVarSep
;
1054 foreach($this->mBidtable
as $k => $v)
1055 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
1056 foreach($this->mUnidtable
as $k => $a)
1057 foreach($a as $from=>$to)
1058 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
1063 * Parse rules conversion
1066 function getRuleConvertedStr($variant,$doConvert){
1067 $bidtable = $this->mBidtable
;
1068 $unidtable = $this->mUnidtable
;
1070 if( count($bidtable) +
count($unidtable) == 0 ){
1071 return $this->mRules
;
1072 } elseif ($doConvert){// the text converted
1073 // display current variant in bidirectional array
1074 $disp = $this->getTextInBidtable($variant);
1075 // or display current variant in fallbacks
1077 $disp = $this->getTextInBidtable(
1078 $this->mConverter
->getVariantFallbacks($variant));
1079 // or display current variant in unidirectional array
1080 if(!$disp && array_key_exists($variant,$unidtable)){
1081 $disp = array_values($unidtable[$variant]);
1084 // or display frist text under disable manual convert
1085 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
1086 if(count($bidtable)>0){
1087 $disp = array_values($bidtable);
1090 $disp = array_values($unidtable);
1091 $disp = array_values($disp[0]);
1096 } else {// no convert
1097 return $this->mRules
;
1102 * generate conversion table for all text
1105 function generateConvTable(){
1106 $flags = $this->mFlags
;
1107 $bidtable = $this->mBidtable
;
1108 $unidtable = $this->mUnidtable
;
1109 $manLevel = $this->mConverter
->mManualLevel
;
1112 foreach($this->mConverter
->mVariants
as $v) {
1113 /* for bidirectional array
1114 fill in the missing variants, if any,
1116 if(!array_key_exists($v, $bidtable)) {
1117 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
1118 $vf = $this->getTextInBidtable($variantFallbacks);
1119 if($vf) $bidtable[$v] = $vf;
1122 if(array_key_exists($v,$bidtable)){
1123 foreach($vmarked as $vo){
1124 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1125 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1126 // to introduce a custom mapping between
1127 // words WordZh and WordTw in the whole text
1128 if($manLevel[$v]=='bidirectional'){
1129 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1131 if($manLevel[$vo]=='bidirectional'){
1132 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1137 /*for unidirectional array
1138 fill to convert tables */
1139 $allow_unid = $manLevel[$v]=='bidirectional'
1140 ||
$manLevel[$v]=='unidirectional';
1141 if($allow_unid && array_key_exists($v,$unidtable)){
1142 $ct=$this->mConvTable
[$v];
1143 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1149 * Parse rules and flags
1152 function parse($variant){
1154 $variant = $this->mConverter
->getPreferredVariant();
1156 $variants = $this->mConverter
->mVariants
;
1157 $this->parseFlags();
1158 $flags = $this->mFlags
;
1160 // convert to specified variant
1161 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1162 if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
1163 if ( in_array( $variant, $flags ) ) // check if current variant in flags
1164 // then convert <text to convert> to current language
1165 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variant );
1166 else { // if current variant no in flags,
1167 // then we check its fallback variants.
1168 $variantFallbacks = $this->mConverter
->getVariantFallbacks($variant);
1169 foreach ( $variantFallbacks as $variantFallback ) {
1170 // if current variant's fallback exist in flags
1171 if ( in_array( $variantFallback, $flags ) ) {
1172 // then convert <text to convert> to fallback language
1173 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variantFallback );
1178 $this->mFlags
= $flags = array('R');
1181 if( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1182 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1183 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1185 $this->parseRules();
1187 $rules = $this->mRules
;
1189 if( count( $this->mBidtable
) == 0 && count( $this->mUnidtable
) == 0 ){
1190 if(in_array('+',$flags) ||
in_array('-',$flags))
1191 // fill all variants if text in -{A/H/-|text} without rules
1192 foreach($this->mConverter
->mVariants
as $v)
1193 $this->mBidtable
[$v] = $rules;
1194 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1195 $this->mFlags
= $flags = array('R');
1198 if( in_array('R',$flags) ) {
1199 // if we don't do content convert, still strip the -{}- tags
1200 $this->mRuleDisplay
= $rules;
1201 } elseif ( in_array('N',$flags) ){
1202 // proces N flag: output current variant name
1203 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1204 } elseif ( in_array('D',$flags) ){
1205 // proces D flag: output rules description
1206 $this->mRuleDisplay
= $this->getRulesDesc();
1207 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1208 // proces H,- flag or T only: output nothing
1209 $this->mRuleDisplay
= '';
1210 } elseif ( in_array('S',$flags) ){
1211 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1212 $this->mConverter
->mDoContentConvert
);
1214 $this->mRuleDisplay
= $this->mManualCodeError
;
1217 if ( in_array('T',$flags) ) {
1218 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1219 $this->mConverter
->mDoTitleConvert
);
1222 if (in_array('-', $flags))
1223 $this->mRulesAction
='remove';
1224 if (in_array('+', $flags))
1225 $this->mRulesAction
='add';
1227 $this->generateConvTable();
1233 function hasRules(){
1238 * get display text on markup -{...}-
1241 function getDisplay(){
1242 return $this->mRuleDisplay
;
1245 * get converted title
1248 function getTitle(){
1249 return $this->mRuleTitle
;
1253 * return how deal with conversion rules
1256 function getRulesAction(){
1257 return $this->mRulesAction
;
1261 * get conversion table ( bidirectional and unidirectional conversion table )
1264 function getConvTable(){
1265 return $this->mConvTable
;
1269 * get conversion rules string
1272 function getRules(){
1273 return $this->mRules
;
1277 * get conversion flags
1280 function getFlags(){
1281 return $this->mFlags
;