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;
58 global $wgDisabledVariants;
59 $this->mVariants
= array();
60 foreach( $variants as $variant ) {
61 if( !in_array( $variant, $wgDisabledVariants ) )
62 $this->mVariants
[] = $variant;
64 $this->mVariantFallbacks
= $variantfallbacks;
65 global $wgLanguageNames;
66 $this->mVariantNames
= $wgLanguageNames;
67 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
71 'unidsep'=>'=>', //for unidirectional conversion
76 $this->mMarkup
= array_merge($m, $markup);
78 // 'S' show converted text
79 // '+' add rules for alltext
80 // 'E' the gave flags is error
81 // these flags above are reserved for program
82 'A'=>'A', // add rule for convert code (all text convert)
83 'T'=>'T', // title convert
84 'R'=>'R', // raw content
85 'D'=>'D', // convert description (subclass implement)
86 '-'=>'-', // remove convert (not implement)
87 'H'=>'H', // add rule for convert code (but no display in placed code )
88 'N'=>'N' // current variant name
90 $this->mFlags
= array_merge($f, $flags);
91 foreach( $this->mVariants
as $v) {
92 $this->mManualLevel
[$v]=array_key_exists($v,$manualLevel)
95 $this->mNamespaceTables
[$v] = array();
96 $this->mFlags
[$v] = $v;
103 function getVariants() {
104 return $this->mVariants
;
108 * in case some variant is not defined in the markup, we need
109 * to have some fallback. for example, in zh, normally people
110 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
111 * when zh-sg is preferred but not defined, we will pick zh-hans
112 * in this case. right now this is only used by zh.
114 * @param string $v the language code of the variant
115 * @return string array the code of the fallback language or false if there is no fallback
118 function getVariantFallbacks($v) {
119 if( isset( $this->mVariantFallbacks
[$v] ) ) {
120 return $this->mVariantFallbacks
[$v];
122 return $this->mMainLanguageCode
;
126 * get preferred language variants.
127 * @param boolean $fromUser Get it from $wgUser's preferences
128 * @return string the preferred language code
131 function getPreferredVariant( $fromUser = true ) {
132 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
134 if($this->mPreferredVariant
)
135 return $this->mPreferredVariant
;
137 // figure out user lang without constructing wgLang to avoid infinite recursion
139 $defaultUserLang = $wgUser->getOption( 'language' );
141 $defaultUserLang = $this->mMainLanguageCode
;
142 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
143 // see if interface language is same as content, if not, prevent conversion
144 if( ! in_array( $userLang, $this->mVariants
) ){
145 $this->mPreferredVariant
= $this->mMainLanguageCode
; // no conversion
146 return $this->mPreferredVariant
;
149 // see if the preference is set in the request
150 $req = $wgRequest->getText( 'variant' );
151 if( in_array( $req, $this->mVariants
) ) {
152 $this->mPreferredVariant
= $req;
156 // check the syntax /code/ArticleTitle
157 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
158 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
159 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
160 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
161 if(in_array($scriptBase,$this->mVariants
)){
162 $this->mPreferredVariant
= $scriptBase;
163 return $this->mPreferredVariant
;
167 // get language variant preference from logged in users
168 // Don't call this on stub objects because that causes infinite
169 // recursion during initialisation
170 if( $fromUser && $wgUser->isLoggedIn() ) {
171 $this->mPreferredVariant
= $wgUser->getOption('variant');
172 return $this->mPreferredVariant
;
175 // see if default variant is globaly set
176 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
177 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
178 return $this->mPreferredVariant
;
181 if( !$this->mPreferredVariant
) {
182 // see if some supported language variant is set in the
183 // http header, but we don't set the mPreferredVariant
184 // variable in case this is called before the user's
185 // preference is loaded
186 if( array_key_exists( 'HTTP_ACCEPT_LANGUAGE', $_SERVER ) ) {
187 $acceptLanguage = strtolower( $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
190 $result = explode(',', $acceptLanguage);
192 $languages = array();
194 foreach( $result as $elem ) {
195 // if $elem likes 'zh-cn;q=0.9'
196 if(($posi = strpos( $elem, ';' )) !== false ) {
197 // get the real language code likes 'zh-cn'
198 $languages[] = substr( $elem, 0, $posi );
201 $languages[] = $elem;
205 $fallback_languages = array();
206 foreach( $languages as $language ) {
208 $language = trim( $language );
209 if( in_array( $language, $this->mVariants
) ) {
213 // To see if there are fallbacks of current language.
214 // We record these fallback variants, and process
216 $fallbacks = $this->getVariantFallbacks( $language );
217 if( is_string( $fallbacks ) )
218 $fallback_languages[] = $fallbacks;
219 elseif( is_array( $fallbacks ) )
220 $fallback_languages = array_merge( $fallback_languages, $fallbacks );
224 // process fallback languages now
225 $fallback_languages = array_unique( $fallback_languages );
226 foreach( $fallback_languages as $language ) {
227 if( in_array( $language, $this->mVariants
) ) {
234 return $this->mMainLanguageCode
;
238 * caption convert, base on preg_replace_callback
240 * to convert text in "title" or "alt", like '<img alt="text" ... '
241 * or '<span title="text" ... '
243 * @return string like ' alt="yyyy"' or ' title="yyyy"'
246 function captionConvert( $matches ) {
247 $toVariant = $this->getPreferredVariant();
248 $title = $matches[1];
250 // we convert captions except URL
251 if( !strpos( $text, '://' ) )
252 $text = $this->translate($text, $toVariant);
253 return " $title=\"$text\"";
257 * dictionary-based conversion
259 * @param string $text the text to be converted
260 * @param string $toVariant the target language code
261 * @return string the converted text
264 function autoConvert($text, $toVariant=false) {
265 $fname="LanguageConverter::autoConvert";
267 wfProfileIn( $fname );
269 if(!$this->mTablesLoaded
)
273 $toVariant = $this->getPreferredVariant();
274 if(!in_array($toVariant, $this->mVariants
))
277 /* we convert everything except:
278 1. html markups (anything between < and >)
280 3. place holders created by the parser
283 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
284 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
288 // this one is needed when the text is inside an html markup
289 $htmlfix = '|<[^>]+$|^[^<>]*>';
291 // disable convert to variants between <code></code> tags
292 $codefix = '<code>.+?<\/code>|';
293 // disable convertsion of <script type="text/javascript"> ... </script>
294 $scriptfix = '<script.*?>.*?<\/script>|';
295 // disable conversion of <pre xxxx> ... </pre>
296 $prefix = '<pre.*?>.*?<\/pre>|';
298 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
300 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
302 $m = array_shift($matches);
304 $ret = $this->translate($m[0], $toVariant);
305 $mstart = $m[1]+
strlen($m[0]);
307 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
308 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
309 foreach($matches as $m) {
310 $mark = substr($text, $mstart, $m[1]-$mstart);
311 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
313 $ret .= $this->translate($m[0], $toVariant);
314 $mstart = $m[1] +
strlen($m[0]);
316 wfProfileOut( $fname );
321 * Translate a string to a variant
322 * Doesn't process markup or do any of that other stuff, for that use convert()
324 * @param string $text Text to convert
325 * @param string $variant Variant language code
326 * @return string Translated text
329 function translate( $text, $variant ) {
330 wfProfileIn( __METHOD__
);
331 if( !$this->mTablesLoaded
)
333 $text = $this->mTables
[$variant]->replace( $text );
334 wfProfileOut( __METHOD__
);
339 * convert text to all supported variants
341 * @param string $text the text to be converted
342 * @return array of string
345 function autoConvertToAllVariants($text) {
346 $fname="LanguageConverter::autoConvertToAllVariants";
347 wfProfileIn( $fname );
348 if( !$this->mTablesLoaded
)
352 foreach($this->mVariants
as $variant) {
353 $ret[$variant] = $this->translate($text, $variant);
356 wfProfileOut( $fname );
361 * convert link text to all supported variants
363 * @param string $text the text to be converted
364 * @return array of string
367 function convertLinkToAllVariants($text) {
368 if( !$this->mTablesLoaded
)
372 $tarray = explode($this->mMarkup
['begin'], $text);
373 $tfirst = array_shift($tarray);
375 foreach($this->mVariants
as $variant)
376 $ret[$variant] = $this->translate($tfirst,$variant);
378 foreach($tarray as $txt) {
379 $marked = explode($this->mMarkup
['end'], $txt, 2);
381 foreach($this->mVariants
as $variant){
382 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
383 if(array_key_exists(1, $marked))
384 $ret[$variant] .= $this->translate($marked[1],$variant);
393 * prepare manual conversion table
396 function applyManualConv( $convRule ){
397 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
398 $title = $convRule->getTitle();
400 $this->mTitleFromFlag
= true;
401 $this->mTitleDisplay
= $title;
404 //apply manual conversion table to global table
405 $convTable = $convRule->getConvTable();
406 $action = $convRule->getRulesAction();
407 foreach( $convTable as $variant => $pair ) {
408 if( !in_array( $variant, $this->mVariants
) )continue;
409 if( $action=="add" ) {
410 foreach( $pair as $from => $to ) {
411 // to ensure that $from and $to not be left blank
412 // so $this->translate() could always return a string
414 // more efficient than array_merge(), about 2.5 times.
415 $this->mTables
[$variant]->setPair( $from, $to );
418 elseif ( $action == "remove" ) {
419 $this->mTables
[$variant]->removeArray( $pair );
425 * Convert text using a parser object for context
428 function parserConvert( $text, &$parser ) {
429 global $wgDisableLangConversion;
430 /* don't do anything if this is the conversion table */
431 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
432 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
437 if ( $wgDisableLangConversion )
440 $text = $this->convert( $text );
442 if ( $this->mTitleFromFlag
)
443 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
449 * @param string $title the title included namespace
450 * @return array of string
453 function convertNamespace( $title, $variant ) {
454 $splittitle = explode( ':', $title );
455 if (count($splittitle) < 2)
457 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) )
458 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
459 $ret = implode(':', $splittitle );
467 function convertTitle( $text, $variant ){
468 global $wgDisableTitleConversion, $wgUser;
470 // check for global param and __NOTC__ tag
471 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
$wgUser->getOption('noconvertlink') == 1 ) {
472 $this->mTitleDisplay
= $text;
476 // use the title from the T flag if any
477 if( $this->mTitleFromFlag
){
478 $this->mTitleFromFlag
= false;
479 return $this->mTitleDisplay
;
483 $isredir = $wgRequest->getText( 'redirect', 'yes' );
484 $action = $wgRequest->getText( 'action' );
485 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
486 if ( $isredir == 'no' ||
$action == 'edit' ||
$action == 'submit' ||
$linkconvert == 'no' ) {
489 $text = $this->convertNamespace( $text, $variant );
490 $this->mTitleDisplay
= $this->convert( $text );
491 return $this->mTitleDisplay
;
496 * convert text to different variants of a language. the automatic
497 * conversion is done in autoConvert(). here we parse the text
498 * marked with -{}-, which specifies special conversions of the
499 * text that can not be accomplished in autoConvert()
501 * syntax of the markup:
502 * -{code1:text1;code2:text2;...}- or
503 * -{flags|code1:text1;code2:text2;...}- or
504 * -{text}- in which case no conversion should take place for text
506 * @param string $text text to be converted
507 * @param bool $isTitle whether this conversion is for the article title
508 * @return string converted text
511 function convert( $text, $isTitle = false ) {
513 $mw =& MagicWord
::get( 'notitleconvert' );
514 if( $mw->matchAndRemove( $text ) )
515 $this->mDoTitleConvert
= false;
516 $mw =& MagicWord
::get( 'nocontentconvert' );
517 if( $mw->matchAndRemove( $text ) ) {
518 $this->mDoContentConvert
= false;
521 // no conversion if redirecting
522 $mw =& MagicWord
::get( 'redirect' );
523 if( $mw->matchStart( $text ) )
526 $plang = $this->getPreferredVariant();
528 // for title convertion
529 if ( $isTitle ) return $this->convertTitle( $text, $plang );
531 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
534 foreach ( $tarray as $txt ) {
536 $marked = explode( $this->mMarkup
['begin'], $txt, 2 );
538 if( $this->mDoContentConvert
)
539 // Bug 19620: should convert a string immediately after a new rule added.
540 $text .= $this->autoConvert( $marked[0], $plang );
544 if ( array_key_exists( 1, $marked ) ) {
545 $crule = new ConverterRule($marked[1], $this);
546 $crule->parse( $plang );
547 $text .= $crule->getDisplay();
548 $this->applyManualConv( $crule );
551 $text .= $this->mMarkup
['end'];
555 // Remove the last delimiter (wasn't real)
556 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
561 * if a language supports multiple variants, it is
562 * possible that non-existing link in one variant
563 * actually exists in another variant. this function
564 * tries to find it. See e.g. LanguageZh.php
566 * @param string $link the name of the link
567 * @param mixed $nt the title object of the link
568 * @param boolean $ignoreOtherCond: to disable other conditions when
569 * we need to transclude a template or update a category's link
570 * @return null the input parameters may be modified upon return
573 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
574 # If the article has already existed, there is no need to
575 # check it again, otherwise it may cause a fault.
576 if ( is_object( $nt ) && $nt->exists() )
579 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
580 $isredir = $wgRequest->getText( 'redirect', 'yes' );
581 $action = $wgRequest->getText( 'action' );
582 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
583 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
584 $linkBatch = new LinkBatch();
588 if ( $disableLinkConversion ||
( !$ignoreOtherCond && ( $isredir == 'no' ||
$action == 'edit'
589 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) )
592 if ( is_object( $nt ) )
593 $ns = $nt->getNamespace();
595 $variants = $this->autoConvertToAllVariants($link);
596 if($variants == false) //give up
601 foreach( $variants as $v ) {
603 $varnt = Title
::newFromText( $v, $ns );
604 if(!is_null($varnt)){
605 $linkBatch->addObj($varnt);
611 // fetch all variants in single query
612 $linkBatch->execute();
614 foreach( $titles as $varnt ) {
615 if( $varnt->getArticleID() > 0 ) {
617 $link = $varnt->getText();
624 * returns language specific hash options
628 function getExtraHashOptions() {
629 $variant = $this->getPreferredVariant();
630 return '!' . $variant ;
634 * get title text as defined in the body of the article text
638 function getParsedTitle() {
639 return $this->mTitleDisplay
;
643 * Load default conversion tables
644 * This method must be implemented in derived class
648 function loadDefaultTables() {
649 $name = get_class($this);
650 wfDie("Must implement loadDefaultTables() method in class $name");
654 * load conversion tables either from the cache or the disk
657 function loadTables($fromcache=true) {
659 if( $this->mTablesLoaded
)
661 wfProfileIn( __METHOD__
);
662 $this->mTablesLoaded
= true;
663 $this->mTables
= false;
665 wfProfileIn( __METHOD__
.'-cache' );
666 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
667 wfProfileOut( __METHOD__
.'-cache' );
669 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
670 wfProfileIn( __METHOD__
.'-recache' );
671 // not in cache, or we need a fresh reload.
672 // we will first load the default tables
673 // then update them using things in MediaWiki:Zhconversiontable/*
674 $this->loadDefaultTables();
675 foreach($this->mVariants
as $var) {
676 $cached = $this->parseCachedTable($var);
677 $this->mTables
[$var]->mergeArray($cached);
680 $this->postLoadTables();
681 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
683 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
684 wfProfileOut( __METHOD__
.'-recache' );
686 wfProfileOut( __METHOD__
);
690 * Hook for post processig after conversion tables are loaded
693 function postLoadTables() {}
696 * Reload the conversion tables
700 function reloadTables() {
702 unset($this->mTables
);
703 $this->mTablesLoaded
= false;
704 $this->loadTables(false);
709 * parse the conversion table stored in the cache
711 * the tables should be in blocks of the following form:
718 * to make the tables more manageable, subpages are allowed
719 * and will be parsed recursively if $recursive=true
722 function parseCachedTable($code, $subpage='', $recursive=true) {
723 global $wgMessageCache;
724 static $parsed = array();
726 if(!is_object($wgMessageCache))
729 $key = 'Conversiontable/'.$code;
731 $key .= '/' . $subpage;
733 if(array_key_exists($key, $parsed))
736 if ( strpos( $code, '/' ) === false ) {
737 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
739 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
740 if ( $title && $title->exists() ) {
741 $article = new Article( $title );
742 $txt = $article->getContents();
748 // get all subpage links of the form
749 // [[MediaWiki:conversiontable/zh-xx/...|...]]
750 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
751 $subs = explode('[[', $txt);
753 foreach( $subs as $sub ) {
754 $link = explode(']]', $sub, 2);
755 if(count($link) != 2)
757 $b = explode('|', $link[0]);
758 $b = explode('/', trim($b[0]), 3);
764 if($b[0] == $linkhead && $b[1] == $code) {
765 $sublinks[] = $sublink;
770 // parse the mappings in this page
771 $blocks = explode($this->mMarkup
['begin'], $txt);
772 array_shift($blocks);
774 foreach($blocks as $block) {
775 $mappings = explode($this->mMarkup
['end'], $block, 2);
776 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
777 $table = explode( ';', $stripped );
778 foreach( $table as $t ) {
779 $m = explode( '=>', $t );
780 if( count( $m ) != 2)
782 // trim any trailling comments starting with '//'
783 $tt = explode('//', $m[1], 2);
784 $ret[trim($m[0])] = trim($tt[0]);
787 $parsed[$key] = true;
790 // recursively parse the subpages
792 foreach($sublinks as $link) {
793 $s = $this->parseCachedTable($code, $link, $recursive);
794 $ret = array_merge($ret, $s);
798 if ($this->mUcfirst
) {
799 foreach ($ret as $k => $v) {
800 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
807 * Enclose a string with the "no conversion" tag. This is used by
808 * various functions in the Parser
810 * @param string $text text to be tagged for no conversion
811 * @return string the tagged text
814 function markNoConversion($text, $noParse=false) {
815 # don't mark if already marked
816 if(strpos($text, $this->mMarkup
['begin']) ||
817 strpos($text, $this->mMarkup
['end']))
820 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
825 * convert the sorting key for category links. this should make different
826 * keys that are variants of each other map to the same key
828 function convertCategoryKey( $key ) {
832 * hook to refresh the cache of conversion tables when
833 * MediaWiki:conversiontable* is updated
836 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
837 $titleobj = $article->getTitle();
838 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
839 $title = $titleobj->getDBkey();
840 $t = explode('/', $title, 3);
842 if( $c > 1 && $t[0] == 'Conversiontable' ) {
843 if(in_array($t[1], $this->mVariants
)) {
844 $this->reloadTables();
852 * Armour rendered math against conversion
853 * Wrap math into rawoutput -{R| math }- syntax
856 function armourMath($text){
857 // we need to convert '-{' and '}-' to '-{' and '}-'
858 // to avoid a unwanted '}-' appeared after the math-image.
859 $text = strtr( $text, array('-{' => '-{', '}-' => '}-') );
860 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
866 * parser for rules of language conversion , parse rules in -{ }- tag
868 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
870 class ConverterRule
{
871 var $mText; // original text in -{text}-
872 var $mConverter; // LanguageConverter object
873 var $mManualCodeError='<strong class="error">code error!</strong>';
874 var $mRuleDisplay = '',$mRuleTitle=false;
875 var $mRules = '';// string : the text of the rules
876 var $mRulesAction = 'none';
877 var $mFlags = array();
878 var $mConvTable = array();
879 var $mBidtable = array();// array of the translation in each variant
880 var $mUnidtable = array();// array of the translation in each variant
885 * @param string $text the text between -{ and }-
886 * @param object $converter a LanguageConverter object
889 function __construct($text,$converter){
890 $this->mText
= $text;
891 $this->mConverter
=$converter;
892 foreach($converter->mVariants
as $v){
893 $this->mConvTable
[$v]=array();
898 * check if variants array in convert array
900 * @param string $variant Variant language code
901 * @return string Translated text
904 function getTextInBidtable($variants){
905 if(is_string($variants)){ $variants=array($variants); }
906 if(!is_array($variants)) return false;
907 foreach ($variants as $variant){
908 if(array_key_exists($variant, $this->mBidtable
)){
909 return $this->mBidtable
[$variant];
916 * Parse flags with syntax -{FLAG| ... }-
919 function parseFlags(){
920 $text = $this->mText
;
921 if(strlen($text) < 2 ) {
922 $this->mFlags
= array( 'R' );
923 $this->mRules
= $text;
928 $markup = $this->mConverter
->mMarkup
;
929 $validFlags = $this->mConverter
->mFlags
;
930 $variants = $this->mConverter
->mVariants
;
932 $tt = explode($markup['flagsep'], $text, 2);
933 if(count($tt) == 2) {
934 $f = explode($markup['varsep'], $tt[0]);
937 if(array_key_exists($ff, $validFlags) &&
938 !in_array($validFlags[$ff], $flags))
939 $flags[] = $validFlags[$ff];
947 if( in_array('R',$flags) ){
948 $flags = array('R');// remove other flags
949 } elseif ( in_array('N',$flags) ){
950 $flags = array('N');// remove other flags
951 } elseif ( in_array('-',$flags) ){
952 $flags = array('-');// remove other flags
953 } elseif (count($flags)==1 && $flags[0]=='T'){
955 } elseif ( in_array('H',$flags) ){
956 // replace A flag, and remove other flags except T
957 $temp=array('+','H');
958 if(in_array('T',$flags)) $temp[] = 'T';
959 if(in_array('D',$flags)) $temp[] = 'D';
962 if ( in_array('A',$flags) ) {
966 if ( in_array('D',$flags) )
967 $flags=array_diff($flags,array('S'));
968 $flags_temp = array();
969 foreach ($variants as $variant) {
970 // try to find flags like "zh-hans", "zh-hant"
971 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
972 if ( in_array($variant, $flags) )
973 $flags_temp[] = $variant;
975 if ( count($flags_temp) !== 0 )
976 $flags = $flags_temp;
978 if ( count($flags) == 0 )
980 $this->mRules
=$rules;
981 $this->mFlags
=$flags;
985 * generate conversion table
988 function parseRules() {
989 $rules = $this->mRules
;
990 $flags = $this->mFlags
;
992 $unidtable = array();
993 $markup = $this->mConverter
->mMarkup
;
994 $variants = $this->mConverter
->mVariants
;
996 // varsep_pattern for preg_split:
997 // text should be splited by ";" only if a valid variant
998 // name exist after the markup, for example:
999 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
1000 // we should split it as:
1002 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1003 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1006 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1007 foreach( $variants as $variant ) {
1008 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
1009 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1010 . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1012 $varsep_pattern .= '\s*$)/';
1014 $choice = preg_split($varsep_pattern, $rules);
1016 foreach( $choice as $c ) {
1017 $v = explode($markup['codesep'], $c, 2);
1018 if( count($v) != 2 )
1019 continue;// syntax error, skip
1022 $u = explode($markup['unidsep'], $v);
1023 // if $to is empty, strtr() could return a wrong result
1024 if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
1025 $bidtable[$v] = $to;
1026 } else if(count($u) == 2){
1027 $from = trim($u[0]);
1029 if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
1030 && $to && in_array( $v, $variants ) )
1031 $unidtable[$v] = array( $from=>$to );
1032 elseif ( $to && in_array( $v, $variants ) )
1033 $unidtable[$v][$from] = $to;
1035 // syntax error, pass
1036 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ){
1037 $bidtable = array();
1038 $unidtable = array();
1042 $this->mBidtable
= $bidtable;
1043 $this->mUnidtable
= $unidtable;
1049 function getRulesDesc(){
1050 $codesep = $this->mConverter
->mDescCodeSep
;
1051 $varsep = $this->mConverter
->mDescVarSep
;
1053 foreach($this->mBidtable
as $k => $v)
1054 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
1055 foreach($this->mUnidtable
as $k => $a)
1056 foreach($a as $from=>$to)
1057 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
1062 * Parse rules conversion
1065 function getRuleConvertedStr($variant,$doConvert){
1066 $bidtable = $this->mBidtable
;
1067 $unidtable = $this->mUnidtable
;
1069 if( count($bidtable) +
count($unidtable) == 0 ){
1070 return $this->mRules
;
1071 } elseif ($doConvert){// the text converted
1072 // display current variant in bidirectional array
1073 $disp = $this->getTextInBidtable($variant);
1074 // or display current variant in fallbacks
1076 $disp = $this->getTextInBidtable(
1077 $this->mConverter
->getVariantFallbacks($variant));
1078 // or display current variant in unidirectional array
1079 if(!$disp && array_key_exists($variant,$unidtable)){
1080 $disp = array_values($unidtable[$variant]);
1083 // or display frist text under disable manual convert
1084 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
1085 if(count($bidtable)>0){
1086 $disp = array_values($bidtable);
1089 $disp = array_values($unidtable);
1090 $disp = array_values($disp[0]);
1095 } else {// no convert
1096 return $this->mRules
;
1101 * generate conversion table for all text
1104 function generateConvTable(){
1105 $flags = $this->mFlags
;
1106 $bidtable = $this->mBidtable
;
1107 $unidtable = $this->mUnidtable
;
1108 $manLevel = $this->mConverter
->mManualLevel
;
1111 foreach($this->mConverter
->mVariants
as $v) {
1112 /* for bidirectional array
1113 fill in the missing variants, if any,
1115 if(!array_key_exists($v, $bidtable)) {
1116 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
1117 $vf = $this->getTextInBidtable($variantFallbacks);
1118 if($vf) $bidtable[$v] = $vf;
1121 if(array_key_exists($v,$bidtable)){
1122 foreach($vmarked as $vo){
1123 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1124 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1125 // to introduce a custom mapping between
1126 // words WordZh and WordTw in the whole text
1127 if($manLevel[$v]=='bidirectional'){
1128 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1130 if($manLevel[$vo]=='bidirectional'){
1131 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1136 /*for unidirectional array
1137 fill to convert tables */
1138 $allow_unid = $manLevel[$v]=='bidirectional'
1139 ||
$manLevel[$v]=='unidirectional';
1140 if($allow_unid && array_key_exists($v,$unidtable)){
1141 $ct=$this->mConvTable
[$v];
1142 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1148 * Parse rules and flags
1151 function parse($variant){
1153 $variant = $this->mConverter
->getPreferredVariant();
1155 $variants = $this->mConverter
->mVariants
;
1156 $this->parseFlags();
1157 $flags = $this->mFlags
;
1159 // convert to specified variant
1160 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1161 if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
1162 if ( in_array( $variant, $flags ) ) // check if current variant in flags
1163 // then convert <text to convert> to current language
1164 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variant );
1165 else { // if current variant no in flags,
1166 // then we check its fallback variants.
1167 $variantFallbacks = $this->mConverter
->getVariantFallbacks($variant);
1168 foreach ( $variantFallbacks as $variantFallback ) {
1169 // if current variant's fallback exist in flags
1170 if ( in_array( $variantFallback, $flags ) ) {
1171 // then convert <text to convert> to fallback language
1172 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variantFallback );
1177 $this->mFlags
= $flags = array('R');
1180 if( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1181 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1182 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1184 $this->parseRules();
1186 $rules = $this->mRules
;
1188 if( count( $this->mBidtable
) == 0 && count( $this->mUnidtable
) == 0 ){
1189 if(in_array('+',$flags) ||
in_array('-',$flags))
1190 // fill all variants if text in -{A/H/-|text} without rules
1191 foreach($this->mConverter
->mVariants
as $v)
1192 $this->mBidtable
[$v] = $rules;
1193 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1194 $this->mFlags
= $flags = array('R');
1197 if( in_array('R',$flags) ) {
1198 // if we don't do content convert, still strip the -{}- tags
1199 $this->mRuleDisplay
= $rules;
1200 } elseif ( in_array('N',$flags) ){
1201 // proces N flag: output current variant name
1202 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1203 } elseif ( in_array('D',$flags) ){
1204 // proces D flag: output rules description
1205 $this->mRuleDisplay
= $this->getRulesDesc();
1206 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1207 // proces H,- flag or T only: output nothing
1208 $this->mRuleDisplay
= '';
1209 } elseif ( in_array('S',$flags) ){
1210 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1211 $this->mConverter
->mDoContentConvert
);
1213 $this->mRuleDisplay
= $this->mManualCodeError
;
1216 if ( in_array('T',$flags) ) {
1217 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1218 $this->mConverter
->mDoTitleConvert
);
1221 if (in_array('-', $flags))
1222 $this->mRulesAction
='remove';
1223 if (in_array('+', $flags))
1224 $this->mRulesAction
='add';
1226 $this->generateConvTable();
1232 function hasRules(){
1237 * get display text on markup -{...}-
1240 function getDisplay(){
1241 return $this->mRuleDisplay
;
1244 * get converted title
1247 function getTitle(){
1248 return $this->mRuleTitle
;
1252 * return how deal with conversion rules
1255 function getRulesAction(){
1256 return $this->mRulesAction
;
1260 * get conversion table ( bidirectional and unidirectional conversion table )
1263 function getConvTable(){
1264 return $this->mConvTable
;
1268 * get conversion rules string
1271 function getRules(){
1272 return $this->mRules
;
1276 * get conversion flags
1279 function getFlags(){
1280 return $this->mFlags
;