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 $mDoTitleConvert=true, $mDoContentConvert=true;
26 var $mManualLevel; // 'bidirectional' 'unidirectional' 'disable' for each variants
27 var $mTitleFromFlag = false;
32 var $mDescCodeSep = ':',$mDescVarSep = ';';
33 var $mUcfirst = false;
34 var $mTitleOriginal = '';
35 var $mTitleDisplay = '';
37 const CACHE_VERSION_KEY
= 'VERSION 6';
42 * @param string $maincode the main language code of this language
43 * @param array $variants the supported variants of this language
44 * @param array $variantfallback the fallback language of each variant
45 * @param array $markup array defining the markup used for manual conversion
46 * @param array $flags array defining the custom strings that maps to the flags
47 * @param array $manualLevel limit for supported variants
50 function __construct( $langobj, $maincode,
52 $variantfallbacks=array(),
55 $manualLevel = array() ) {
56 $this->mLangObj
= $langobj;
57 $this->mMainLanguageCode
= $maincode;
59 global $wgDisabledVariants;
60 $this->mVariants
= array();
61 foreach( $variants as $variant ) {
62 if( !in_array( $variant, $wgDisabledVariants ) )
63 $this->mVariants
[] = $variant;
65 $this->mVariantFallbacks
= $variantfallbacks;
66 global $wgLanguageNames;
67 $this->mVariantNames
= $wgLanguageNames;
68 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
72 'unidsep'=>'=>', //for unidirectional conversion
77 $this->mMarkup
= array_merge($m, $markup);
79 // 'S' show converted text
80 // '+' add rules for alltext
81 // 'E' the gave flags is error
82 // these flags above are reserved for program
83 'A'=>'A', // add rule for convert code (all text convert)
84 'T'=>'T', // title convert
85 'R'=>'R', // raw content
86 'D'=>'D', // convert description (subclass implement)
87 '-'=>'-', // remove convert (not implement)
88 'H'=>'H', // add rule for convert code (but no display in placed code )
89 'N'=>'N' // current variant name
91 $this->mFlags
= array_merge($f, $flags);
92 foreach( $this->mVariants
as $v) {
93 $this->mManualLevel
[$v]=array_key_exists($v,$manualLevel)
96 $this->mNamespaceTables
[$v] = array();
97 $this->mFlags
[$v] = $v;
104 function getVariants() {
105 return $this->mVariants
;
109 * in case some variant is not defined in the markup, we need
110 * to have some fallback. for example, in zh, normally people
111 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
112 * when zh-sg is preferred but not defined, we will pick zh-hans
113 * in this case. right now this is only used by zh.
115 * @param string $v the language code of the variant
116 * @return string array the code of the fallback language or false if there is no fallback
119 function getVariantFallbacks($v) {
120 if( isset( $this->mVariantFallbacks
[$v] ) ) {
121 return $this->mVariantFallbacks
[$v];
123 return $this->mMainLanguageCode
;
127 * get preferred language variants.
128 * @param boolean $fromUser Get it from $wgUser's preferences
129 * @return string the preferred language code
132 function getPreferredVariant( $fromUser = true ) {
133 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
135 if($this->mPreferredVariant
)
136 return $this->mPreferredVariant
;
138 // figure out user lang without constructing wgLang to avoid infinite recursion
140 $defaultUserLang = $wgUser->getOption( 'language' );
142 $defaultUserLang = $this->mMainLanguageCode
;
143 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
144 // see if interface language is same as content, if not, prevent conversion
145 if( ! in_array( $userLang, $this->mVariants
) ){
146 $this->mPreferredVariant
= $this->mMainLanguageCode
; // no conversion
147 return $this->mPreferredVariant
;
150 // see if the preference is set in the request
151 $req = $wgRequest->getText( 'variant' );
152 if( in_array( $req, $this->mVariants
) ) {
153 $this->mPreferredVariant
= $req;
157 // check the syntax /code/ArticleTitle
158 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
159 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
160 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
161 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
162 if(in_array($scriptBase,$this->mVariants
)){
163 $this->mPreferredVariant
= $scriptBase;
164 return $this->mPreferredVariant
;
168 // get language variant preference from logged in users
169 // Don't call this on stub objects because that causes infinite
170 // recursion during initialisation
171 if( $fromUser && $wgUser->isLoggedIn() ) {
172 $this->mPreferredVariant
= $wgUser->getOption('variant');
173 return $this->mPreferredVariant
;
176 // see if default variant is globaly set
177 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
178 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
179 return $this->mPreferredVariant
;
182 if( !$this->mPreferredVariant
) {
183 // see if some supported language variant is set in the
184 // http header, but we don't set the mPreferredVariant
185 // variable in case this is called before the user's
186 // preference is loaded
187 if( array_key_exists( 'HTTP_ACCEPT_LANGUAGE', $_SERVER ) ) {
189 $acceptLanguage = strtolower( $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
191 $result = explode(',', $acceptLanguage);
193 $languages = array();
195 foreach( $result as $elem ) {
196 // if $elem likes 'zh-cn;q=0.9'
197 if(($posi = strpos( $elem, ';' )) !== false ) {
198 // get the real language code likes 'zh-cn'
199 $languages[] = substr( $elem, 0, $posi );
202 $languages[] = $elem;
206 $fallback_languages = array();
207 $ret_language = null;
208 foreach( $languages as $language ) {
210 $language = trim( $language );
211 if( in_array( $language, $this->mVariants
) ) {
212 $ret_language = $language;
216 // To see if there are fallbacks of current language.
217 // We record these fallback variants, and process
219 $fallbacks = $this->getVariantFallbacks( $language );
220 if( is_string( $fallbacks ) )
221 $fallback_languages[] = $fallbacks;
222 elseif( is_array( $fallbacks ) )
223 $fallback_languages = array_merge( $fallback_languages, $fallbacks );
227 // process fallback languages now
228 if( $ret_language === null ) {
229 $fallback_languages = array_unique( $fallback_languages );
230 foreach( $fallback_languages as $language ) {
231 if( in_array( $language, $this->mVariants
) ) {
232 $ret_language = $language;
238 // bug 21672: Add Accept-Language to Vary and XVO headers
239 // to help Squid to determine user's perferred local language
240 // ONLY add Accept-Language when a variant has been found out
241 // thanks to Liangent's help
242 if( $ret_language !== $this->mMainLanguageCode
) {
244 $wgOut->addVaryHeader( 'Accept-Language', array('string-contains=' .$ret_language) );
246 return $ret_language;
250 return $this->mMainLanguageCode
;
254 * caption convert, base on preg_replace_callback
256 * to convert text in "title" or "alt", like '<img alt="text" ... '
257 * or '<span title="text" ... '
259 * @return string like ' alt="yyyy"' or ' title="yyyy"'
262 function captionConvert( $matches ) {
263 $toVariant = $this->getPreferredVariant();
264 $title = $matches[1];
266 // we convert captions except URL
267 if( !strpos( $text, '://' ) )
268 $text = $this->translate($text, $toVariant);
269 return " $title=\"$text\"";
273 * dictionary-based conversion
275 * @param string $text the text to be converted
276 * @param string $toVariant the target language code
277 * @return string the converted text
280 function autoConvert($text, $toVariant=false) {
281 $fname="LanguageConverter::autoConvert";
283 wfProfileIn( $fname );
285 if(!$this->mTablesLoaded
)
289 $toVariant = $this->getPreferredVariant();
290 if(!in_array($toVariant, $this->mVariants
))
293 /* we convert everything except:
294 1. html markups (anything between < and >)
296 3. place holders created by the parser
299 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
300 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
304 // this one is needed when the text is inside an html markup
305 $htmlfix = '|<[^>]+$|^[^<>]*>';
307 // disable convert to variants between <code></code> tags
308 $codefix = '<code>.+?<\/code>|';
309 // disable convertsion of <script type="text/javascript"> ... </script>
310 $scriptfix = '<script.*?>.*?<\/script>|';
311 // disable conversion of <pre xxxx> ... </pre>
312 $prefix = '<pre.*?>.*?<\/pre>|';
314 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
316 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
318 $m = array_shift($matches);
320 $ret = $this->translate($m[0], $toVariant);
321 $mstart = $m[1]+
strlen($m[0]);
323 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
324 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
329 foreach($matches as $m) {
330 $mark = substr($text, $mstart, $m[1]-$mstart);
331 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
332 // Let's convert the trtext only once,
333 // it would give us more performance improvement
335 $trtext .= $m[0] . $trtextmark;
336 $mstart = $m[1] +
strlen($m[0]);
339 $trtext = $this->translate( $trtext, $toVariant );
340 $trtext = StringUtils
::explode( $trtextmark, $trtext );
341 foreach( $trtext as $t ) {
342 $ret .= array_shift($notrtext);
345 wfProfileOut( $fname );
350 * Translate a string to a variant
351 * Doesn't process markup or do any of that other stuff, for that use convert()
353 * @param string $text Text to convert
354 * @param string $variant Variant language code
355 * @return string Translated text
358 function translate( $text, $variant ) {
359 wfProfileIn( __METHOD__
);
360 // If $text is empty or only includes spaces, do nothing
361 // Otherwise translate it
363 if( !$this->mTablesLoaded
)
365 $text = $this->mTables
[$variant]->replace( $text );
367 wfProfileOut( __METHOD__
);
372 * convert text to all supported variants
374 * @param string $text the text to be converted
375 * @return array of string
378 function autoConvertToAllVariants($text) {
379 $fname="LanguageConverter::autoConvertToAllVariants";
380 wfProfileIn( $fname );
381 if( !$this->mTablesLoaded
)
385 foreach($this->mVariants
as $variant) {
386 $ret[$variant] = $this->translate($text, $variant);
389 wfProfileOut( $fname );
394 * convert link text to all supported variants
396 * @param string $text the text to be converted
397 * @return array of string
400 function convertLinkToAllVariants($text) {
401 if( !$this->mTablesLoaded
)
405 $tarray = explode($this->mMarkup
['begin'], $text);
406 $tfirst = array_shift($tarray);
408 foreach($this->mVariants
as $variant)
409 $ret[$variant] = $this->translate($tfirst,$variant);
411 foreach($tarray as $txt) {
412 $marked = explode($this->mMarkup
['end'], $txt, 2);
414 foreach($this->mVariants
as $variant){
415 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
416 if(array_key_exists(1, $marked))
417 $ret[$variant] .= $this->translate($marked[1],$variant);
426 * prepare manual conversion table
429 function applyManualConv( $convRule ){
430 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
431 $title = $convRule->getTitle();
433 $this->mTitleFromFlag
= true;
434 $this->mTitleDisplay
= $title;
437 //apply manual conversion table to global table
438 $convTable = $convRule->getConvTable();
439 $action = $convRule->getRulesAction();
440 foreach( $convTable as $variant => $pair ) {
441 if( !in_array( $variant, $this->mVariants
) )continue;
442 if( $action == 'add' ) {
443 foreach( $pair as $from => $to ) {
444 // to ensure that $from and $to not be left blank
445 // so $this->translate() could always return a string
447 // more efficient than array_merge(), about 2.5 times.
448 $this->mTables
[$variant]->setPair( $from, $to );
451 elseif ( $action == 'remove' ) {
452 $this->mTables
[$variant]->removeArray( $pair );
458 * Convert text using a parser object for context
461 function parserConvert( $text, &$parser ) {
462 global $wgDisableLangConversion;
463 /* don't do anything if this is the conversion table */
464 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
465 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
470 if ( $wgDisableLangConversion )
473 $text = $this->convert( $text );
475 $this->convertTitle();
476 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
483 * @param string $title the title included namespace
484 * @return array of string
487 function convertNamespace( $title, $variant ) {
488 $splittitle = explode( ':', $title );
489 if (count($splittitle) < 2)
491 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) )
492 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
493 $ret = implode(':', $splittitle );
498 * Pre convert title. Store the original title $this->mTitleOrginal;
499 * store the default converted title to $this->mTitleDisplay.
502 function preConvertTitle( $text, $variant ){
503 $this->mTitleOriginal
= $text;
505 $text = $this->convertNamespace( $text, $variant );
506 $this->mTitleDisplay
= $this->convert( $text );
513 function convertTitle(){
514 global $wgDisableTitleConversion, $wgUser, $wgRequest;
515 $isredir = $wgRequest->getText( 'redirect', 'yes' );
516 $action = $wgRequest->getText( 'action' );
517 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
519 // check for the global variable, __NOTC__ magic word, and user setting
520 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
521 $wgUser->getOption('noconvertlink') == 1 ) {
522 $this->mTitleDisplay
= $this->mTitleOriginal
;
525 // check for GET params
526 elseif ( $isredir == 'no' ||
$action == 'edit' ||
$linkconvert == 'no' ) {
527 $this->mTitleDisplay
= $this->mTitleOriginal
;
532 * convert text to different variants of a language. the automatic
533 * conversion is done in autoConvert(). here we parse the text
534 * marked with -{}-, which specifies special conversions of the
535 * text that can not be accomplished in autoConvert()
537 * syntax of the markup:
538 * -{code1:text1;code2:text2;...}- or
539 * -{flags|code1:text1;code2:text2;...}- or
540 * -{text}- in which case no conversion should take place for text
542 * @param string $text text to be converted
543 * @param bool $isTitle whether this conversion is for the article title
544 * @return string converted text
547 function convert( $text, $isTitle = false ) {
549 $mw =& MagicWord
::get( 'notitleconvert' );
550 if( $mw->matchAndRemove( $text ) )
551 $this->mDoTitleConvert
= false;
552 $mw =& MagicWord
::get( 'nocontentconvert' );
553 if( $mw->matchAndRemove( $text ) ) {
554 $this->mDoContentConvert
= false;
557 // no conversion if redirecting
558 $mw =& MagicWord
::get( 'redirect' );
559 if( $mw->matchStart( $text ) )
562 $plang = $this->getPreferredVariant();
564 // for title convertion
566 $this->preConvertTitle( $text, $plang );
570 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
573 foreach ( $tarray as $txt ) {
575 $marked = explode( $this->mMarkup
['begin'], $txt, 2 );
577 if( $this->mDoContentConvert
)
578 // Bug 19620: should convert a string immediately after a new rule added.
579 $text .= $this->autoConvert( $marked[0], $plang );
583 if ( array_key_exists( 1, $marked ) ) {
584 $crule = new ConverterRule($marked[1], $this);
585 $crule->parse( $plang );
586 $text .= $crule->getDisplay();
587 $this->applyManualConv( $crule );
590 $text .= $this->mMarkup
['end'];
594 // Remove the last delimiter (wasn't real)
595 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
600 * if a language supports multiple variants, it is
601 * possible that non-existing link in one variant
602 * actually exists in another variant. this function
603 * tries to find it. See e.g. LanguageZh.php
605 * @param string $link the name of the link
606 * @param mixed $nt the title object of the link
607 * @param boolean $ignoreOtherCond: to disable other conditions when
608 * we need to transclude a template or update a category's link
609 * @return null the input parameters may be modified upon return
612 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
613 # If the article has already existed, there is no need to
614 # check it again, otherwise it may cause a fault.
615 if ( is_object( $nt ) && $nt->exists() )
618 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
619 $isredir = $wgRequest->getText( 'redirect', 'yes' );
620 $action = $wgRequest->getText( 'action' );
621 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
622 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
623 $linkBatch = new LinkBatch();
627 if ( $disableLinkConversion ||
( !$ignoreOtherCond && ( $isredir == 'no' ||
$action == 'edit'
628 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) )
631 if ( is_object( $nt ) )
632 $ns = $nt->getNamespace();
634 $variants = $this->autoConvertToAllVariants($link);
635 if($variants == false) //give up
640 foreach( $variants as $v ) {
642 $varnt = Title
::newFromText( $v, $ns );
643 if(!is_null($varnt)){
644 $linkBatch->addObj($varnt);
650 // fetch all variants in single query
651 $linkBatch->execute();
653 foreach( $titles as $varnt ) {
654 if( $varnt->getArticleID() > 0 ) {
656 $link = $varnt->getText();
663 * returns language specific hash options
667 function getExtraHashOptions() {
668 $variant = $this->getPreferredVariant();
669 return '!' . $variant ;
673 * get title text as defined in the body of the article text
677 function getParsedTitle() {
678 return $this->mTitleDisplay
;
682 * Load default conversion tables
683 * This method must be implemented in derived class
687 function loadDefaultTables() {
688 $name = get_class($this);
689 wfDie("Must implement loadDefaultTables() method in class $name");
693 * load conversion tables either from the cache or the disk
696 function loadTables($fromcache=true) {
698 if( $this->mTablesLoaded
)
700 wfProfileIn( __METHOD__
);
701 $this->mTablesLoaded
= true;
702 $this->mTables
= false;
704 wfProfileIn( __METHOD__
.'-cache' );
705 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
706 wfProfileOut( __METHOD__
.'-cache' );
708 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
709 wfProfileIn( __METHOD__
.'-recache' );
710 // not in cache, or we need a fresh reload.
711 // we will first load the default tables
712 // then update them using things in MediaWiki:Zhconversiontable/*
713 $this->loadDefaultTables();
714 foreach($this->mVariants
as $var) {
715 $cached = $this->parseCachedTable($var);
716 $this->mTables
[$var]->mergeArray($cached);
719 $this->postLoadTables();
720 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
722 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
723 wfProfileOut( __METHOD__
.'-recache' );
725 wfProfileOut( __METHOD__
);
729 * Hook for post processig after conversion tables are loaded
732 function postLoadTables() {}
735 * Reload the conversion tables
739 function reloadTables() {
741 unset($this->mTables
);
742 $this->mTablesLoaded
= false;
743 $this->loadTables(false);
748 * parse the conversion table stored in the cache
750 * the tables should be in blocks of the following form:
757 * to make the tables more manageable, subpages are allowed
758 * and will be parsed recursively if $recursive=true
761 function parseCachedTable($code, $subpage='', $recursive=true) {
762 global $wgMessageCache;
763 static $parsed = array();
765 if(!is_object($wgMessageCache))
768 $key = 'Conversiontable/'.$code;
770 $key .= '/' . $subpage;
772 if(array_key_exists($key, $parsed))
775 if ( strpos( $code, '/' ) === false ) {
776 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
778 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
779 if ( $title && $title->exists() ) {
780 $article = new Article( $title );
781 $txt = $article->getContents();
787 // get all subpage links of the form
788 // [[MediaWiki:conversiontable/zh-xx/...|...]]
789 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
790 $subs = explode('[[', $txt);
792 foreach( $subs as $sub ) {
793 $link = explode(']]', $sub, 2);
794 if(count($link) != 2)
796 $b = explode('|', $link[0]);
797 $b = explode('/', trim($b[0]), 3);
803 if($b[0] == $linkhead && $b[1] == $code) {
804 $sublinks[] = $sublink;
809 // parse the mappings in this page
810 $blocks = explode($this->mMarkup
['begin'], $txt);
811 array_shift($blocks);
813 foreach($blocks as $block) {
814 $mappings = explode($this->mMarkup
['end'], $block, 2);
815 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
816 $table = explode( ';', $stripped );
817 foreach( $table as $t ) {
818 $m = explode( '=>', $t );
819 if( count( $m ) != 2)
821 // trim any trailling comments starting with '//'
822 $tt = explode('//', $m[1], 2);
823 $ret[trim($m[0])] = trim($tt[0]);
826 $parsed[$key] = true;
829 // recursively parse the subpages
831 foreach($sublinks as $link) {
832 $s = $this->parseCachedTable($code, $link, $recursive);
833 $ret = array_merge($ret, $s);
837 if ($this->mUcfirst
) {
838 foreach ($ret as $k => $v) {
839 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
846 * Enclose a string with the "no conversion" tag. This is used by
847 * various functions in the Parser
849 * @param string $text text to be tagged for no conversion
850 * @return string the tagged text
853 function markNoConversion($text, $noParse=false) {
854 # don't mark if already marked
855 if(strpos($text, $this->mMarkup
['begin']) ||
856 strpos($text, $this->mMarkup
['end']))
859 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
864 * convert the sorting key for category links. this should make different
865 * keys that are variants of each other map to the same key
867 function convertCategoryKey( $key ) {
871 * hook to refresh the cache of conversion tables when
872 * MediaWiki:conversiontable* is updated
875 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
876 $titleobj = $article->getTitle();
877 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
878 $title = $titleobj->getDBkey();
879 $t = explode('/', $title, 3);
881 if( $c > 1 && $t[0] == 'Conversiontable' ) {
882 if(in_array($t[1], $this->mVariants
)) {
883 $this->reloadTables();
891 * Armour rendered math against conversion
892 * Wrap math into rawoutput -{R| math }- syntax
895 function armourMath($text){
896 // we need to convert '-{' and '}-' to '-{' and '}-'
897 // to avoid a unwanted '}-' appeared after the math-image.
898 $text = strtr( $text, array('-{' => '-{', '}-' => '}-') );
899 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
905 * parser for rules of language conversion , parse rules in -{ }- tag
907 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
909 class ConverterRule
{
910 var $mText; // original text in -{text}-
911 var $mConverter; // LanguageConverter object
912 var $mManualCodeError = '<strong class="error">code error!</strong>';
913 var $mRuleDisplay = '';
914 var $mRuleTitle = false;
915 var $mRules = '';// string : the text of the rules
916 var $mRulesAction = 'none';
917 var $mFlags = array();
918 var $mConvTable = array();
919 var $mBidtable = array();// array of the translation in each variant
920 var $mUnidtable = array();// array of the translation in each variant
925 * @param string $text the text between -{ and }-
926 * @param object $converter a LanguageConverter object
929 function __construct( $text, $converter ){
930 $this->mText
= $text;
931 $this->mConverter
= $converter;
932 foreach( $converter->mVariants
as $v ){
933 $this->mConvTable
[$v] = array();
938 * check if variants array in convert array
940 * @param string $variant Variant language code
941 * @return string Translated text
944 function getTextInBidtable( $variants ){
945 if( is_string( $variants ) ){ $variants = array( $variants ); }
946 if( !is_array( $variants ) ) return false;
947 foreach( $variants as $variant ){
948 if( array_key_exists( $variant, $this->mBidtable
) ){
949 return $this->mBidtable
[$variant];
956 * Parse flags with syntax -{FLAG| ... }-
959 function parseFlags(){
960 $text = $this->mText
;
961 if(strlen($text) < 2 ) {
962 $this->mFlags
= array( 'R' );
963 $this->mRules
= $text;
968 $markup = $this->mConverter
->mMarkup
;
969 $validFlags = $this->mConverter
->mFlags
;
970 $variants = $this->mConverter
->mVariants
;
972 $tt = explode($markup['flagsep'], $text, 2);
973 if(count($tt) == 2) {
974 $f = explode($markup['varsep'], $tt[0]);
977 if(array_key_exists($ff, $validFlags) &&
978 !in_array($validFlags[$ff], $flags))
979 $flags[] = $validFlags[$ff];
987 if( in_array('R',$flags) ){
988 $flags = array('R');// remove other flags
989 } elseif ( in_array('N',$flags) ){
990 $flags = array('N');// remove other flags
991 } elseif ( in_array('-',$flags) ){
992 $flags = array('-');// remove other flags
993 } elseif (count($flags)==1 && $flags[0]=='T'){
995 } elseif ( in_array('H',$flags) ){
996 // replace A flag, and remove other flags except T
997 $temp=array('+','H');
998 if(in_array('T',$flags)) $temp[] = 'T';
999 if(in_array('D',$flags)) $temp[] = 'D';
1002 if ( in_array('A',$flags) ) {
1006 if ( in_array('D',$flags) )
1007 $flags=array_diff($flags,array('S'));
1008 $flags_temp = array();
1009 foreach ($variants as $variant) {
1010 // try to find flags like "zh-hans", "zh-hant"
1011 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1012 if ( in_array($variant, $flags) )
1013 $flags_temp[] = $variant;
1015 if ( count($flags_temp) !== 0 )
1016 $flags = $flags_temp;
1018 if ( count($flags) == 0 )
1019 $flags = array('S');
1020 $this->mRules
=$rules;
1021 $this->mFlags
=$flags;
1025 * generate conversion table
1028 function parseRules() {
1029 $rules = $this->mRules
;
1030 $flags = $this->mFlags
;
1031 $bidtable = array();
1032 $unidtable = array();
1033 $markup = $this->mConverter
->mMarkup
;
1034 $variants = $this->mConverter
->mVariants
;
1036 // varsep_pattern for preg_split:
1037 // text should be splited by ";" only if a valid variant
1038 // name exist after the markup, for example:
1039 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
1040 // we should split it as:
1042 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1043 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1046 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1047 foreach( $variants as $variant ) {
1048 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
1049 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1050 . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1052 $varsep_pattern .= '\s*$)/';
1054 $choice = preg_split($varsep_pattern, $rules);
1056 foreach( $choice as $c ) {
1057 $v = explode($markup['codesep'], $c, 2);
1058 if( count($v) != 2 )
1059 continue;// syntax error, skip
1062 $u = explode($markup['unidsep'], $v, 2);
1063 // if $to is empty, strtr() could return a wrong result
1064 if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
1065 $bidtable[$v] = $to;
1066 } else if(count($u) == 2){
1067 $from = trim($u[0]);
1069 if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
1070 && $to && in_array( $v, $variants ) )
1071 $unidtable[$v] = array( $from=>$to );
1072 elseif ( $to && in_array( $v, $variants ) )
1073 $unidtable[$v][$from] = $to;
1075 // syntax error, pass
1076 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ){
1077 $bidtable = array();
1078 $unidtable = array();
1082 $this->mBidtable
= $bidtable;
1083 $this->mUnidtable
= $unidtable;
1089 function getRulesDesc(){
1090 $codesep = $this->mConverter
->mDescCodeSep
;
1091 $varsep = $this->mConverter
->mDescVarSep
;
1093 foreach($this->mBidtable
as $k => $v)
1094 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
1095 foreach($this->mUnidtable
as $k => $a)
1096 foreach($a as $from=>$to)
1097 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
1102 * Parse rules conversion
1105 function getRuleConvertedStr( $variant, $doConvert ){
1106 $bidtable = $this->mBidtable
;
1107 $unidtable = $this->mUnidtable
;
1109 if( count($bidtable) +
count($unidtable) == 0 ){
1110 return $this->mRules
;
1111 } elseif ( $doConvert ){// the text converted
1112 // display current variant in bidirectional array
1113 $disp = $this->getTextInBidtable($variant);
1114 // or display current variant in fallbacks
1116 $disp = $this->getTextInBidtable(
1117 $this->mConverter
->getVariantFallbacks($variant));
1118 // or display current variant in unidirectional array
1119 if(!$disp && array_key_exists($variant,$unidtable)){
1120 $disp = array_values($unidtable[$variant]);
1123 // or display frist text under disable manual convert
1124 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
1125 if(count($bidtable)>0){
1126 $disp = array_values($bidtable);
1129 $disp = array_values($unidtable);
1130 $disp = array_values($disp[0]);
1135 } else {// no convert
1136 return $this->mRules
;
1141 * generate conversion table for all text
1144 function generateConvTable(){
1145 $flags = $this->mFlags
;
1146 $bidtable = $this->mBidtable
;
1147 $unidtable = $this->mUnidtable
;
1148 $manLevel = $this->mConverter
->mManualLevel
;
1151 foreach($this->mConverter
->mVariants
as $v) {
1152 /* for bidirectional array
1153 fill in the missing variants, if any,
1155 if(!array_key_exists($v, $bidtable)) {
1156 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
1157 $vf = $this->getTextInBidtable($variantFallbacks);
1158 if($vf) $bidtable[$v] = $vf;
1161 if(array_key_exists($v,$bidtable)){
1162 foreach($vmarked as $vo){
1163 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1164 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1165 // to introduce a custom mapping between
1166 // words WordZh and WordTw in the whole text
1167 if($manLevel[$v]=='bidirectional'){
1168 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1170 if($manLevel[$vo]=='bidirectional'){
1171 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1176 /*for unidirectional array
1177 fill to convert tables */
1178 $allow_unid = $manLevel[$v]=='bidirectional'
1179 ||
$manLevel[$v]=='unidirectional';
1180 if( $allow_unid && array_key_exists( $v, $unidtable ) ){
1181 $ct = $this->mConvTable
[$v];
1182 $this->mConvTable
[$v] = array_merge($ct, $unidtable[$v]);
1188 * Parse rules and flags
1191 function parse($variant){
1193 $variant = $this->mConverter
->getPreferredVariant();
1195 $variants = $this->mConverter
->mVariants
;
1196 $this->parseFlags();
1197 $flags = $this->mFlags
;
1199 // convert to specified variant
1200 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1201 if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
1202 if ( in_array( $variant, $flags ) ) // check if current variant in flags
1203 // then convert <text to convert> to current language
1204 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variant );
1205 else { // if current variant no in flags,
1206 // then we check its fallback variants.
1207 $variantFallbacks = $this->mConverter
->getVariantFallbacks($variant);
1208 foreach ( $variantFallbacks as $variantFallback ) {
1209 // if current variant's fallback exist in flags
1210 if ( in_array( $variantFallback, $flags ) ) {
1211 // then convert <text to convert> to fallback language
1212 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variantFallback );
1217 $this->mFlags
= $flags = array('R');
1220 if( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1221 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1222 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1224 $this->parseRules();
1226 $rules = $this->mRules
;
1228 if( count( $this->mBidtable
) == 0 && count( $this->mUnidtable
) == 0 ){
1229 if(in_array('+',$flags) ||
in_array('-',$flags))
1230 // fill all variants if text in -{A/H/-|text} without rules
1231 foreach($this->mConverter
->mVariants
as $v)
1232 $this->mBidtable
[$v] = $rules;
1233 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1234 $this->mFlags
= $flags = array('R');
1237 if( in_array('R',$flags) ) {
1238 // if we don't do content convert, still strip the -{}- tags
1239 $this->mRuleDisplay
= $rules;
1240 } elseif ( in_array('N',$flags) ){
1241 // proces N flag: output current variant name
1242 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1243 } elseif ( in_array('D',$flags) ){
1244 // proces D flag: output rules description
1245 $this->mRuleDisplay
= $this->getRulesDesc();
1246 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1247 // proces H,- flag or T only: output nothing
1248 $this->mRuleDisplay
= '';
1249 } elseif ( in_array('S',$flags) ){
1250 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1251 $this->mConverter
->mDoContentConvert
);
1253 $this->mRuleDisplay
= $this->mManualCodeError
;
1256 if ( in_array('T',$flags) ) {
1257 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1258 $this->mConverter
->mDoTitleConvert
);
1261 if (in_array('-', $flags))
1262 $this->mRulesAction
='remove';
1263 if (in_array('+', $flags))
1264 $this->mRulesAction
='add';
1266 $this->generateConvTable();
1272 function hasRules(){
1277 * get display text on markup -{...}-
1280 function getDisplay(){
1281 return $this->mRuleDisplay
;
1284 * get converted title
1287 function getTitle(){
1288 return $this->mRuleTitle
;
1292 * return how deal with conversion rules
1295 function getRulesAction(){
1296 return $this->mRulesAction
;
1300 * get conversion table ( bidirectional and unidirectional conversion table )
1303 function getConvTable(){
1304 return $this->mConvTable
;
1308 * get conversion rules string
1311 function getRules(){
1312 return $this->mRules
;
1316 * get conversion flags
1319 function getFlags(){
1320 return $this->mFlags
;