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
) ) {
203 $this->mPreferredVariant
= $language;
204 return $this->mPreferredVariant
;
210 return $this->mMainLanguageCode
;
214 * caption convert, base on preg_replace_callback
216 * to convert text in "title" or "alt", like '<img alt="text" ... '
217 * or '<span title="text" ... '
219 * @return string like ' alt="yyyy"' or ' title="yyyy"'
222 function captionConvert( $matches ) {
223 $toVariant = $this->getPreferredVariant();
224 $title = $matches[1];
226 // we convert captions except URL
227 if( !strpos( $text, '://' ) )
228 $text = $this->translate($text, $toVariant);
229 return " $title=\"$text\"";
233 * dictionary-based conversion
235 * @param string $text the text to be converted
236 * @param string $toVariant the target language code
237 * @return string the converted text
240 function autoConvert($text, $toVariant=false) {
241 $fname="LanguageConverter::autoConvert";
243 wfProfileIn( $fname );
245 if(!$this->mTablesLoaded
)
249 $toVariant = $this->getPreferredVariant();
250 if(!in_array($toVariant, $this->mVariants
))
253 /* we convert everything except:
254 1. html markups (anything between < and >)
256 3. place holders created by the parser
259 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
260 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
264 // this one is needed when the text is inside an html markup
265 $htmlfix = '|<[^>]+$|^[^<>]*>';
267 // disable convert to variants between <code></code> tags
268 $codefix = '<code>.+?<\/code>|';
269 // disable convertsion of <script type="text/javascript"> ... </script>
270 $scriptfix = '<script.*?>.*?<\/script>|';
271 // disable conversion of <pre xxxx> ... </pre>
272 $prefix = '<pre.*?>.*?<\/pre>|';
274 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
276 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
278 $m = array_shift($matches);
280 $ret = $this->translate($m[0], $toVariant);
281 $mstart = $m[1]+
strlen($m[0]);
283 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
284 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
285 foreach($matches as $m) {
286 $mark = substr($text, $mstart, $m[1]-$mstart);
287 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
289 $ret .= $this->translate($m[0], $toVariant);
290 $mstart = $m[1] +
strlen($m[0]);
292 wfProfileOut( $fname );
297 * Translate a string to a variant
298 * Doesn't process markup or do any of that other stuff, for that use convert()
300 * @param string $text Text to convert
301 * @param string $variant Variant language code
302 * @return string Translated text
305 function translate( $text, $variant ) {
306 wfProfileIn( __METHOD__
);
307 if( !$this->mTablesLoaded
)
309 $text = $this->mTables
[$variant]->replace( $text );
310 wfProfileOut( __METHOD__
);
315 * convert text to all supported variants
317 * @param string $text the text to be converted
318 * @return array of string
321 function autoConvertToAllVariants($text) {
322 $fname="LanguageConverter::autoConvertToAllVariants";
323 wfProfileIn( $fname );
324 if( !$this->mTablesLoaded
)
328 foreach($this->mVariants
as $variant) {
329 $ret[$variant] = $this->translate($text, $variant);
332 wfProfileOut( $fname );
337 * convert link text to all supported variants
339 * @param string $text the text to be converted
340 * @return array of string
343 function convertLinkToAllVariants($text) {
344 if( !$this->mTablesLoaded
)
348 $tarray = explode($this->mMarkup
['begin'], $text);
349 $tfirst = array_shift($tarray);
351 foreach($this->mVariants
as $variant)
352 $ret[$variant] = $this->translate($tfirst,$variant);
354 foreach($tarray as $txt) {
355 $marked = explode($this->mMarkup
['end'], $txt, 2);
357 foreach($this->mVariants
as $variant){
358 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
359 if(array_key_exists(1, $marked))
360 $ret[$variant] .= $this->translate($marked[1],$variant);
369 * prepare manual conversion table
372 function applyManualConv( $convRule ){
373 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
374 $title = $convRule->getTitle();
376 $this->mTitleFromFlag
= true;
377 $this->mTitleDisplay
= $title;
380 //apply manual conversion table to global table
381 $convTable = $convRule->getConvTable();
382 $action = $convRule->getRulesAction();
383 foreach( $convTable as $variant => $pair ) {
384 if( !in_array( $variant, $this->mVariants
) )continue;
385 if( $action=="add" ) {
386 foreach( $pair as $from => $to ) {
387 // to ensure that $from and $to not be left blank
388 // so $this->translate() could always return a string
390 // more efficient than array_merge(), about 2.5 times.
391 $this->mTables
[$variant]->setPair( $from, $to );
394 elseif ( $action == "remove" ) {
395 $this->mTables
[$variant]->removeArray( $pair );
401 * Convert text using a parser object for context
404 function parserConvert( $text, &$parser ) {
405 global $wgDisableLangConversion;
406 /* don't do anything if this is the conversion table */
407 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
408 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
413 if ( $wgDisableLangConversion )
416 $text = $this->convert( $text );
418 if ( $this->mTitleFromFlag
)
419 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
425 * @param string $title the title included namespace
426 * @return array of string
429 function convertNamespace( $title, $variant ) {
430 $splittitle = explode( ':', $title );
431 if (count($splittitle) < 2)
433 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) )
434 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
435 $ret = implode(':', $splittitle );
443 function convertTitle( $text, $variant ){
444 global $wgDisableTitleConversion, $wgUser;
446 // check for global param and __NOTC__ tag
447 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
$wgUser->getOption('noconvertlink') == 1 ) {
448 $this->mTitleDisplay
= $text;
452 // use the title from the T flag if any
453 if( $this->mTitleFromFlag
){
454 $this->mTitleFromFlag
= false;
455 return $this->mTitleDisplay
;
459 $isredir = $wgRequest->getText( 'redirect', 'yes' );
460 $action = $wgRequest->getText( 'action' );
461 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
462 if ( $isredir == 'no' ||
$action == 'edit' ||
$action == 'submit' ||
$linkconvert == 'no' ) {
465 $text = $this->convertNamespace( $text, $variant );
466 $this->mTitleDisplay
= $this->convert( $text );
467 return $this->mTitleDisplay
;
472 * convert text to different variants of a language. the automatic
473 * conversion is done in autoConvert(). here we parse the text
474 * marked with -{}-, which specifies special conversions of the
475 * text that can not be accomplished in autoConvert()
477 * syntax of the markup:
478 * -{code1:text1;code2:text2;...}- or
479 * -{flags|code1:text1;code2:text2;...}- or
480 * -{text}- in which case no conversion should take place for text
482 * @param string $text text to be converted
483 * @param bool $isTitle whether this conversion is for the article title
484 * @return string converted text
487 function convert( $text, $isTitle = false ) {
489 $mw =& MagicWord
::get( 'notitleconvert' );
490 if( $mw->matchAndRemove( $text ) )
491 $this->mDoTitleConvert
= false;
492 $mw =& MagicWord
::get( 'nocontentconvert' );
493 if( $mw->matchAndRemove( $text ) ) {
494 $this->mDoContentConvert
= false;
497 // no conversion if redirecting
498 $mw =& MagicWord
::get( 'redirect' );
499 if( $mw->matchStart( $text ) )
502 $plang = $this->getPreferredVariant();
504 // for title convertion
505 if ( $isTitle ) return $this->convertTitle( $text, $plang );
507 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
510 foreach ( $tarray as $txt ) {
512 $marked = explode( $this->mMarkup
['begin'], $txt, 2 );
514 if( $this->mDoContentConvert
)
515 // Bug 19620: should convert a string immediately after a new rule added.
516 $text .= $this->autoConvert( $marked[0], $plang );
518 if ( array_key_exists( 1, $marked ) ) {
519 $crule = new ConverterRule($marked[1], $this);
520 $crule->parse( $plang );
521 $text .= $crule->getDisplay();
522 $this->applyManualConv( $crule );
525 $text .= $this->mMarkup
['end'];
529 // Remove the last delimiter (wasn't real)
530 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
536 * if a language supports multiple variants, it is
537 * possible that non-existing link in one variant
538 * actually exists in another variant. this function
539 * tries to find it. See e.g. LanguageZh.php
541 * @param string $link the name of the link
542 * @param mixed $nt the title object of the link
543 * @param boolean $ignoreOtherCond: to disable other conditions when
544 * we need to transclude a template or update a category's link
545 * @return null the input parameters may be modified upon return
548 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
549 # If the article has already existed, there is no need to
550 # check it again, otherwise it may cause a fault.
554 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
555 $isredir = $wgRequest->getText( 'redirect', 'yes' );
556 $action = $wgRequest->getText( 'action' );
557 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
558 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
559 $linkBatch = new LinkBatch();
563 if ( $disableLinkConversion ||
( !$ignoreOtherCond && ( $isredir == 'no' ||
$action == 'edit'
564 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) )
567 if ( is_object( $nt ) )
568 $ns = $nt->getNamespace();
570 $variants = $this->autoConvertToAllVariants($link);
571 if($variants == false) //give up
576 foreach( $variants as $v ) {
578 $varnt = Title
::newFromText( $v, $ns );
579 if(!is_null($varnt)){
580 $linkBatch->addObj($varnt);
586 // fetch all variants in single query
587 $linkBatch->execute();
589 foreach( $titles as $varnt ) {
590 if( $varnt->getArticleID() > 0 ) {
592 $link = $varnt->getText();
599 * returns language specific hash options
603 function getExtraHashOptions() {
604 $variant = $this->getPreferredVariant();
605 return '!' . $variant ;
609 * get title text as defined in the body of the article text
613 function getParsedTitle() {
614 return $this->mTitleDisplay
;
618 * a write lock to the cache
622 function lockCache() {
625 for($i=0; $i<30; $i++
) {
626 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
638 function unlockCache() {
640 $wgMemc->delete($this->mCacheKey
. "lock");
645 * Load default conversion tables
646 * This method must be implemented in derived class
650 function loadDefaultTables() {
651 $name = get_class($this);
652 wfDie("Must implement loadDefaultTables() method in class $name");
656 * load conversion tables either from the cache or the disk
659 function loadTables($fromcache=true) {
661 if( $this->mTablesLoaded
)
663 wfProfileIn( __METHOD__
);
664 $this->mTablesLoaded
= true;
665 $this->mTables
= false;
667 wfProfileIn( __METHOD__
.'-cache' );
668 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
669 wfProfileOut( __METHOD__
.'-cache' );
671 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
672 wfProfileIn( __METHOD__
.'-recache' );
673 // not in cache, or we need a fresh reload.
674 // we will first load the default tables
675 // then update them using things in MediaWiki:Zhconversiontable/*
676 $this->loadDefaultTables();
677 foreach($this->mVariants
as $var) {
678 $cached = $this->parseCachedTable($var);
679 $this->mTables
[$var]->mergeArray($cached);
682 $this->postLoadTables();
683 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
685 if($this->lockCache()) {
686 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
687 $this->unlockCache();
689 wfProfileOut( __METHOD__
.'-recache' );
691 wfProfileOut( __METHOD__
);
695 * Hook for post processig after conversion tables are loaded
698 function postLoadTables() {}
701 * Reload the conversion tables
705 function reloadTables() {
707 unset($this->mTables
);
708 $this->mTablesLoaded
= false;
709 $this->loadTables(false);
714 * parse the conversion table stored in the cache
716 * the tables should be in blocks of the following form:
723 * to make the tables more manageable, subpages are allowed
724 * and will be parsed recursively if $recursive=true
727 function parseCachedTable($code, $subpage='', $recursive=true) {
728 global $wgMessageCache;
729 static $parsed = array();
731 if(!is_object($wgMessageCache))
734 $key = 'Conversiontable/'.$code;
736 $key .= '/' . $subpage;
738 if(array_key_exists($key, $parsed))
741 if ( strpos( $code, '/' ) === false ) {
742 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
744 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
745 if ( $title && $title->exists() ) {
746 $article = new Article( $title );
747 $txt = $article->getContents();
753 // get all subpage links of the form
754 // [[MediaWiki:conversiontable/zh-xx/...|...]]
755 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
756 $subs = explode('[[', $txt);
758 foreach( $subs as $sub ) {
759 $link = explode(']]', $sub, 2);
760 if(count($link) != 2)
762 $b = explode('|', $link[0]);
763 $b = explode('/', trim($b[0]), 3);
769 if($b[0] == $linkhead && $b[1] == $code) {
770 $sublinks[] = $sublink;
775 // parse the mappings in this page
776 $blocks = explode($this->mMarkup
['begin'], $txt);
777 array_shift($blocks);
779 foreach($blocks as $block) {
780 $mappings = explode($this->mMarkup
['end'], $block, 2);
781 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
782 $table = explode( ';', $stripped );
783 foreach( $table as $t ) {
784 $m = explode( '=>', $t );
785 if( count( $m ) != 2)
787 // trim any trailling comments starting with '//'
788 $tt = explode('//', $m[1], 2);
789 $ret[trim($m[0])] = trim($tt[0]);
792 $parsed[$key] = true;
795 // recursively parse the subpages
797 foreach($sublinks as $link) {
798 $s = $this->parseCachedTable($code, $link, $recursive);
799 $ret = array_merge($ret, $s);
803 if ($this->mUcfirst
) {
804 foreach ($ret as $k => $v) {
805 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
812 * Enclose a string with the "no conversion" tag. This is used by
813 * various functions in the Parser
815 * @param string $text text to be tagged for no conversion
816 * @return string the tagged text
819 function markNoConversion($text, $noParse=false) {
820 # don't mark if already marked
821 if(strpos($text, $this->mMarkup
['begin']) ||
822 strpos($text, $this->mMarkup
['end']))
825 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
830 * convert the sorting key for category links. this should make different
831 * keys that are variants of each other map to the same key
833 function convertCategoryKey( $key ) {
837 * hook to refresh the cache of conversion tables when
838 * MediaWiki:conversiontable* is updated
841 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
842 $titleobj = $article->getTitle();
843 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
844 $title = $titleobj->getDBkey();
845 $t = explode('/', $title, 3);
847 if( $c > 1 && $t[0] == 'Conversiontable' ) {
848 if(in_array($t[1], $this->mVariants
)) {
849 $this->reloadTables();
857 * Armour rendered math against conversion
858 * Wrap math into rawoutput -{R| math }- syntax
861 function armourMath($text){
862 // we need to convert '-{' and '}-' to '-{' and '}-'
863 // to avoid a unwanted '}-' appeared after the math-image.
864 $text = strtr( $text, array('-{' => '-{', '}-' => '}-') );
865 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
871 * parser for rules of language conversion , parse rules in -{ }- tag
873 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
875 class ConverterRule
{
876 var $mText; // original text in -{text}-
877 var $mConverter; // LanguageConverter object
878 var $mManualCodeError='<strong class="error">code error!</strong>';
879 var $mRuleDisplay = '',$mRuleTitle=false;
880 var $mRules = '';// string : the text of the rules
881 var $mRulesAction = 'none';
882 var $mFlags = array();
883 var $mConvTable = array();
884 var $mBidtable = array();// array of the translation in each variant
885 var $mUnidtable = array();// array of the translation in each variant
890 * @param string $text the text between -{ and }-
891 * @param object $converter a LanguageConverter object
894 function __construct($text,$converter){
895 $this->mText
= $text;
896 $this->mConverter
=$converter;
897 foreach($converter->mVariants
as $v){
898 $this->mConvTable
[$v]=array();
903 * check if variants array in convert array
905 * @param string $variant Variant language code
906 * @return string Translated text
909 function getTextInBidtable($variants){
910 if(is_string($variants)){ $variants=array($variants); }
911 if(!is_array($variants)) return false;
912 foreach ($variants as $variant){
913 if(array_key_exists($variant, $this->mBidtable
)){
914 return $this->mBidtable
[$variant];
921 * Parse flags with syntax -{FLAG| ... }-
924 function parseFlags(){
925 $text = $this->mText
;
926 if(strlen($text) < 2 ) {
927 $this->mFlags
= array( 'R' );
928 $this->mRules
= $text;
933 $markup = $this->mConverter
->mMarkup
;
934 $validFlags = $this->mConverter
->mFlags
;
935 $variants = $this->mConverter
->mVariants
;
937 $tt = explode($markup['flagsep'], $text, 2);
938 if(count($tt) == 2) {
939 $f = explode($markup['varsep'], $tt[0]);
942 if(array_key_exists($ff, $validFlags) &&
943 !in_array($validFlags[$ff], $flags))
944 $flags[] = $validFlags[$ff];
952 if( in_array('R',$flags) ){
953 $flags = array('R');// remove other flags
954 } elseif ( in_array('N',$flags) ){
955 $flags = array('N');// remove other flags
956 } elseif ( in_array('-',$flags) ){
957 $flags = array('-');// remove other flags
958 } elseif (count($flags)==1 && $flags[0]=='T'){
960 } elseif ( in_array('H',$flags) ){
961 // replace A flag, and remove other flags except T
962 $temp=array('+','H');
963 if(in_array('T',$flags)) $temp[] = 'T';
964 if(in_array('D',$flags)) $temp[] = 'D';
967 if ( in_array('A',$flags) ) {
971 if ( in_array('D',$flags) )
972 $flags=array_diff($flags,array('S'));
973 $flags_temp = array();
974 foreach ($variants as $variant) {
975 // try to find flags like "zh-hans", "zh-hant"
976 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
977 if ( in_array($variant, $flags) )
978 $flags_temp[] = $variant;
980 if ( count($flags_temp) !== 0 )
981 $flags = $flags_temp;
983 if ( count($flags) == 0 )
985 $this->mRules
=$rules;
986 $this->mFlags
=$flags;
990 * generate conversion table
993 function parseRules() {
994 $rules = $this->mRules
;
995 $flags = $this->mFlags
;
997 $unidtable = array();
998 $markup = $this->mConverter
->mMarkup
;
999 $variants = $this->mConverter
->mVariants
;
1001 // varsep_pattern for preg_split:
1002 // text should be splited by ";" only if a valid variant
1003 // name exist after the markup, for example:
1004 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
1005 // we should split it as:
1007 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1008 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1011 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1012 foreach( $variants as $variant ) {
1013 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
1014 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1015 . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1017 $varsep_pattern .= '\s*$)/';
1019 $choice = preg_split($varsep_pattern, $rules);
1021 foreach( $choice as $c ) {
1022 $v = explode($markup['codesep'], $c, 2);
1023 if( count($v) != 2 )
1024 continue;// syntax error, skip
1027 $u = explode($markup['unidsep'], $v);
1028 // if $to is empty, strtr() could return a wrong result
1029 if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
1030 $bidtable[$v] = $to;
1031 } else if(count($u) == 2){
1032 $from = trim($u[0]);
1034 if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
1035 && $to && in_array( $v, $variants ) )
1036 $unidtable[$v] = array( $from=>$to );
1037 elseif ( $to && in_array( $v, $variants ) )
1038 $unidtable[$v][$from] = $to;
1040 // syntax error, pass
1041 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ){
1042 $bidtable = array();
1043 $unidtable = array();
1047 $this->mBidtable
= $bidtable;
1048 $this->mUnidtable
= $unidtable;
1054 function getRulesDesc(){
1055 $codesep = $this->mConverter
->mDescCodeSep
;
1056 $varsep = $this->mConverter
->mDescVarSep
;
1058 foreach($this->mBidtable
as $k => $v)
1059 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
1060 foreach($this->mUnidtable
as $k => $a)
1061 foreach($a as $from=>$to)
1062 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
1067 * Parse rules conversion
1070 function getRuleConvertedStr($variant,$doConvert){
1071 $bidtable = $this->mBidtable
;
1072 $unidtable = $this->mUnidtable
;
1074 if( count($bidtable) +
count($unidtable) == 0 ){
1075 return $this->mRules
;
1076 } elseif ($doConvert){// the text converted
1077 // display current variant in bidirectional array
1078 $disp = $this->getTextInBidtable($variant);
1079 // or display current variant in fallbacks
1081 $disp = $this->getTextInBidtable(
1082 $this->mConverter
->getVariantFallbacks($variant));
1083 // or display current variant in unidirectional array
1084 if(!$disp && array_key_exists($variant,$unidtable)){
1085 $disp = array_values($unidtable[$variant]);
1088 // or display frist text under disable manual convert
1089 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
1090 if(count($bidtable)>0){
1091 $disp = array_values($bidtable);
1094 $disp = array_values($unidtable);
1095 $disp = array_values($disp[0]);
1100 } else {// no convert
1101 return $this->mRules
;
1106 * generate conversion table for all text
1109 function generateConvTable(){
1110 $flags = $this->mFlags
;
1111 $bidtable = $this->mBidtable
;
1112 $unidtable = $this->mUnidtable
;
1113 $manLevel = $this->mConverter
->mManualLevel
;
1116 foreach($this->mConverter
->mVariants
as $v) {
1117 /* for bidirectional array
1118 fill in the missing variants, if any,
1120 if(!array_key_exists($v, $bidtable)) {
1121 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
1122 $vf = $this->getTextInBidtable($variantFallbacks);
1123 if($vf) $bidtable[$v] = $vf;
1126 if(array_key_exists($v,$bidtable)){
1127 foreach($vmarked as $vo){
1128 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1129 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1130 // to introduce a custom mapping between
1131 // words WordZh and WordTw in the whole text
1132 if($manLevel[$v]=='bidirectional'){
1133 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1135 if($manLevel[$vo]=='bidirectional'){
1136 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1141 /*for unidirectional array
1142 fill to convert tables */
1143 $allow_unid = $manLevel[$v]=='bidirectional'
1144 ||
$manLevel[$v]=='unidirectional';
1145 if($allow_unid && array_key_exists($v,$unidtable)){
1146 $ct=$this->mConvTable
[$v];
1147 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1153 * Parse rules and flags
1156 function parse($variant){
1158 $variant = $this->mConverter
->getPreferredVariant();
1160 $variants = $this->mConverter
->mVariants
;
1161 $this->parseFlags();
1162 $flags = $this->mFlags
;
1164 // convert to specified variant
1165 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1166 if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
1167 if ( in_array( $variant, $flags ) ) // check if current variant in flags
1168 // then convert <text to convert> to current language
1169 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variant );
1170 else { // if current variant no in flags,
1171 // then we check its fallback variants.
1172 $variantFallbacks = $this->mConverter
->getVariantFallbacks($variant);
1173 foreach ( $variantFallbacks as $variantFallback ) {
1174 // if current variant's fallback exist in flags
1175 if ( in_array( $variantFallback, $flags ) ) {
1176 // then convert <text to convert> to fallback language
1177 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variantFallback );
1182 $this->mFlags
= $flags = array('R');
1185 if( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1186 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1187 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1189 $this->parseRules();
1191 $rules = $this->mRules
;
1193 if( count( $this->mBidtable
) == 0 && count( $this->mUnidtable
) == 0 ){
1194 if(in_array('+',$flags) ||
in_array('-',$flags))
1195 // fill all variants if text in -{A/H/-|text} without rules
1196 foreach($this->mConverter
->mVariants
as $v)
1197 $this->mBidtable
[$v] = $rules;
1198 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1199 $this->mFlags
= $flags = array('R');
1202 if( in_array('R',$flags) ) {
1203 // if we don't do content convert, still strip the -{}- tags
1204 $this->mRuleDisplay
= $rules;
1205 } elseif ( in_array('N',$flags) ){
1206 // proces N flag: output current variant name
1207 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1208 } elseif ( in_array('D',$flags) ){
1209 // proces D flag: output rules description
1210 $this->mRuleDisplay
= $this->getRulesDesc();
1211 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1212 // proces H,- flag or T only: output nothing
1213 $this->mRuleDisplay
= '';
1214 } elseif ( in_array('S',$flags) ){
1215 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1216 $this->mConverter
->mDoContentConvert
);
1218 $this->mRuleDisplay
= $this->mManualCodeError
;
1221 if ( in_array('T',$flags) ) {
1222 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1223 $this->mConverter
->mDoTitleConvert
);
1226 if (in_array('-', $flags))
1227 $this->mRulesAction
='remove';
1228 if (in_array('+', $flags))
1229 $this->mRulesAction
='add';
1231 $this->generateConvTable();
1237 function hasRules(){
1242 * get display text on markup -{...}-
1245 function getDisplay(){
1246 return $this->mRuleDisplay
;
1249 * get converted title
1252 function getTitle(){
1253 return $this->mRuleTitle
;
1257 * return how deal with conversion rules
1260 function getRulesAction(){
1261 return $this->mRulesAction
;
1265 * get conversion table ( bidirectional and unidirectional conversion table )
1268 function getConvTable(){
1269 return $this->mConvTable
;
1273 * get conversion rules string
1276 function getRules(){
1277 return $this->mRules
;
1281 * get conversion flags
1284 function getFlags(){
1285 return $this->mFlags
;