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 * @param boolean $fromHeader Get it from Accept-Language
130 * @return string the preferred language code
133 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
134 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant, $wgOut;
136 // bug 21974, don't return $this->mPreferredVariant if $fromUser = false
137 if( $fromUser && $this->mPreferredVariant
)
138 return $this->mPreferredVariant
;
140 // figure out user lang without constructing wgLang to avoid infinite recursion
142 $defaultUserLang = $wgUser->getOption( 'language' );
144 $defaultUserLang = $this->mMainLanguageCode
;
145 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
146 // see if interface language is same as content, if not, prevent conversion
147 if( ! in_array( $userLang, $this->mVariants
) ){
148 $this->mPreferredVariant
= $this->mMainLanguageCode
; // no conversion
149 return $this->mPreferredVariant
;
152 // see if the preference is set in the request
153 $req = $wgRequest->getText( 'variant' );
154 if( in_array( $req, $this->mVariants
) ) {
155 $this->mPreferredVariant
= $req;
159 // check the syntax /code/ArticleTitle
160 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
161 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
162 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
163 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
164 if(in_array($scriptBase,$this->mVariants
)){
165 $this->mPreferredVariant
= $scriptBase;
166 return $this->mPreferredVariant
;
170 // get language variant preference from logged in users
171 // Don't call this on stub objects because that causes infinite
172 // recursion during initialisation
173 if( $fromUser && $wgUser->isLoggedIn() ) {
174 $this->mPreferredVariant
= $wgUser->getOption('variant');
175 return $this->mPreferredVariant
;
178 // see if default variant is globaly set
179 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
180 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
181 return $this->mPreferredVariant
;
184 if( !$this->mPreferredVariant
) {
185 // see if some supported language variant is set in the
186 // http header, but we don't set the mPreferredVariant
187 // variable in case this is called before the user's
188 // preference is loaded
189 if( $fromHeader && array_key_exists( 'HTTP_ACCEPT_LANGUAGE', $_SERVER ) ) {
190 $acceptLanguage = strtolower( $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
192 $result = explode(',', $acceptLanguage);
194 $languages = array();
196 foreach( $result as $elem ) {
197 // if $elem likes 'zh-cn;q=0.9'
198 if(($posi = strpos( $elem, ';' )) !== false ) {
199 // get the real language code likes 'zh-cn'
200 $languages[] = substr( $elem, 0, $posi );
203 $languages[] = $elem;
207 $fallback_languages = array();
208 foreach( $languages as $language ) {
210 $language = trim( $language );
211 if( in_array( $language, $this->mVariants
) ) {
215 // To see if there are fallbacks of current language.
216 // We record these fallback variants, and process
218 $fallbacks = $this->getVariantFallbacks( $language );
219 if( is_string( $fallbacks ) )
220 $fallback_languages[] = $fallbacks;
221 elseif( is_array( $fallbacks ) )
222 $fallback_languages = array_merge( $fallback_languages, $fallbacks );
226 // process fallback languages now
227 $fallback_languages = array_unique( $fallback_languages );
228 foreach( $fallback_languages as $language ) {
229 if( in_array( $language, $this->mVariants
) ) {
235 return $this->mMainLanguageCode
;
239 * caption convert, base on preg_replace_callback
241 * to convert text in "title" or "alt", like '<img alt="text" ... '
242 * or '<span title="text" ... '
244 * @return string like ' alt="yyyy"' or ' title="yyyy"'
247 function captionConvert( $matches ) {
248 $toVariant = $this->getPreferredVariant();
249 $title = $matches[1];
251 // we convert captions except URL
252 if( !strpos( $text, '://' ) )
253 $text = $this->translate($text, $toVariant);
254 return " $title=\"$text\"";
258 * dictionary-based conversion
260 * @param string $text the text to be converted
261 * @param string $toVariant the target language code
262 * @return string the converted text
265 function autoConvert($text, $toVariant=false) {
266 $fname="LanguageConverter::autoConvert";
268 wfProfileIn( $fname );
270 if(!$this->mTablesLoaded
)
274 $toVariant = $this->getPreferredVariant();
275 if(!in_array($toVariant, $this->mVariants
))
278 /* we convert everything except:
279 1. html markups (anything between < and >)
281 3. place holders created by the parser
284 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
285 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
289 // this one is needed when the text is inside an html markup
290 $htmlfix = '|<[^>]+$|^[^<>]*>';
292 // disable convert to variants between <code></code> tags
293 $codefix = '<code>.+?<\/code>|';
294 // disable convertsion of <script type="text/javascript"> ... </script>
295 $scriptfix = '<script.*?>.*?<\/script>|';
296 // disable conversion of <pre xxxx> ... </pre>
297 $prefix = '<pre.*?>.*?<\/pre>|';
299 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
301 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
303 $m = array_shift($matches);
305 $ret = $this->translate($m[0], $toVariant);
306 $mstart = $m[1]+
strlen($m[0]);
308 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
309 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
314 foreach($matches as $m) {
315 $mark = substr($text, $mstart, $m[1]-$mstart);
316 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
317 // Let's convert the trtext only once,
318 // it would give us more performance improvement
320 $trtext .= $m[0] . $trtextmark;
321 $mstart = $m[1] +
strlen($m[0]);
324 $trtext = $this->translate( $trtext, $toVariant );
325 $trtext = StringUtils
::explode( $trtextmark, $trtext );
326 foreach( $trtext as $t ) {
327 $ret .= array_shift($notrtext);
330 wfProfileOut( $fname );
335 * Translate a string to a variant
336 * Doesn't process markup or do any of that other stuff, for that use convert()
338 * @param string $text Text to convert
339 * @param string $variant Variant language code
340 * @return string Translated text
343 function translate( $text, $variant ) {
344 wfProfileIn( __METHOD__
);
345 // If $text is empty or only includes spaces, do nothing
346 // Otherwise translate it
348 if( !$this->mTablesLoaded
)
350 $text = $this->mTables
[$variant]->replace( $text );
352 wfProfileOut( __METHOD__
);
357 * convert text to all supported variants
359 * @param string $text the text to be converted
360 * @return array of string
363 function autoConvertToAllVariants($text) {
364 $fname="LanguageConverter::autoConvertToAllVariants";
365 wfProfileIn( $fname );
366 if( !$this->mTablesLoaded
)
370 foreach($this->mVariants
as $variant) {
371 $ret[$variant] = $this->translate($text, $variant);
374 wfProfileOut( $fname );
379 * convert link text to all supported variants
381 * @param string $text the text to be converted
382 * @return array of string
385 function convertLinkToAllVariants($text) {
386 if( !$this->mTablesLoaded
)
390 $tarray = explode($this->mMarkup
['begin'], $text);
391 $tfirst = array_shift($tarray);
393 foreach($this->mVariants
as $variant)
394 $ret[$variant] = $this->translate($tfirst,$variant);
396 foreach($tarray as $txt) {
397 $marked = explode($this->mMarkup
['end'], $txt, 2);
399 foreach($this->mVariants
as $variant){
400 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
401 if(array_key_exists(1, $marked))
402 $ret[$variant] .= $this->translate($marked[1],$variant);
411 * prepare manual conversion table
414 function applyManualConv( $convRule ){
415 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
416 $title = $convRule->getTitle();
418 $this->mTitleFromFlag
= true;
419 $this->mTitleDisplay
= $title;
422 //apply manual conversion table to global table
423 $convTable = $convRule->getConvTable();
424 $action = $convRule->getRulesAction();
425 foreach( $convTable as $variant => $pair ) {
426 if( !in_array( $variant, $this->mVariants
) )continue;
427 if( $action == 'add' ) {
428 foreach( $pair as $from => $to ) {
429 // to ensure that $from and $to not be left blank
430 // so $this->translate() could always return a string
432 // more efficient than array_merge(), about 2.5 times.
433 $this->mTables
[$variant]->setPair( $from, $to );
436 elseif ( $action == 'remove' ) {
437 $this->mTables
[$variant]->removeArray( $pair );
443 * Convert text using a parser object for context
446 function parserConvert( $text, &$parser ) {
447 global $wgDisableLangConversion;
448 /* don't do anything if this is the conversion table */
449 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
450 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
455 if ( $wgDisableLangConversion )
458 $text = $this->convert( $text );
460 $this->convertTitle();
461 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
468 * @param string $title the title included namespace
469 * @return array of string
472 function convertNamespace( $title, $variant ) {
473 $splittitle = explode( ':', $title );
474 if (count($splittitle) < 2)
476 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) )
477 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
478 $ret = implode(':', $splittitle );
483 * Pre convert title. Store the original title $this->mTitleOrginal;
484 * store the default converted title to $this->mTitleDisplay.
487 function preConvertTitle( $text, $variant ){
488 $this->mTitleOriginal
= $text;
490 $text = $this->convertNamespace( $text, $variant );
491 $this->mTitleDisplay
= $this->convert( $text );
498 function convertTitle(){
499 global $wgDisableTitleConversion, $wgUser, $wgRequest;
500 $isredir = $wgRequest->getText( 'redirect', 'yes' );
501 $action = $wgRequest->getText( 'action' );
502 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
504 // check for the global variable, __NOTC__ magic word, and user setting
505 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
506 $wgUser->getOption('noconvertlink') == 1 ) {
507 $this->mTitleDisplay
= $this->mTitleOriginal
;
510 // check for GET params
511 elseif ( $isredir == 'no' ||
$action == 'edit' ||
$linkconvert == 'no' ) {
512 $this->mTitleDisplay
= $this->mTitleOriginal
;
517 * convert text to different variants of a language. the automatic
518 * conversion is done in autoConvert(). here we parse the text
519 * marked with -{}-, which specifies special conversions of the
520 * text that can not be accomplished in autoConvert()
522 * syntax of the markup:
523 * -{code1:text1;code2:text2;...}- or
524 * -{flags|code1:text1;code2:text2;...}- or
525 * -{text}- in which case no conversion should take place for text
527 * @param string $text text to be converted
528 * @param bool $isTitle whether this conversion is for the article title
529 * @return string converted text
532 function convert( $text, $isTitle = false ) {
534 $mw =& MagicWord
::get( 'notitleconvert' );
535 if( $mw->matchAndRemove( $text ) )
536 $this->mDoTitleConvert
= false;
537 $mw =& MagicWord
::get( 'nocontentconvert' );
538 if( $mw->matchAndRemove( $text ) ) {
539 $this->mDoContentConvert
= false;
542 // no conversion if redirecting
543 $mw =& MagicWord
::get( 'redirect' );
544 if( $mw->matchStart( $text ) )
547 $plang = $this->getPreferredVariant();
549 // for title convertion
551 $this->preConvertTitle( $text, $plang );
555 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
558 foreach ( $tarray as $txt ) {
560 $marked = explode( $this->mMarkup
['begin'], $txt, 2 );
562 if( $this->mDoContentConvert
)
563 // Bug 19620: should convert a string immediately after a new rule added.
564 $text .= $this->autoConvert( $marked[0], $plang );
568 if ( array_key_exists( 1, $marked ) ) {
569 $crule = new ConverterRule($marked[1], $this);
570 $crule->parse( $plang );
571 $text .= $crule->getDisplay();
572 $this->applyManualConv( $crule );
575 $text .= $this->mMarkup
['end'];
579 // Remove the last delimiter (wasn't real)
580 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
585 * if a language supports multiple variants, it is
586 * possible that non-existing link in one variant
587 * actually exists in another variant. this function
588 * tries to find it. See e.g. LanguageZh.php
590 * @param string $link the name of the link
591 * @param mixed $nt the title object of the link
592 * @param boolean $ignoreOtherCond: to disable other conditions when
593 * we need to transclude a template or update a category's link
594 * @return null the input parameters may be modified upon return
597 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
598 # If the article has already existed, there is no need to
599 # check it again, otherwise it may cause a fault.
600 if ( is_object( $nt ) && $nt->exists() )
603 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
604 $isredir = $wgRequest->getText( 'redirect', 'yes' );
605 $action = $wgRequest->getText( 'action' );
606 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
607 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
608 $linkBatch = new LinkBatch();
612 if ( $disableLinkConversion ||
( !$ignoreOtherCond && ( $isredir == 'no' ||
$action == 'edit'
613 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) )
616 if ( is_object( $nt ) )
617 $ns = $nt->getNamespace();
619 $variants = $this->autoConvertToAllVariants($link);
620 if($variants == false) //give up
625 foreach( $variants as $v ) {
627 $varnt = Title
::newFromText( $v, $ns );
628 if(!is_null($varnt)){
629 $linkBatch->addObj($varnt);
635 // fetch all variants in single query
636 $linkBatch->execute();
638 foreach( $titles as $varnt ) {
639 if( $varnt->getArticleID() > 0 ) {
641 $link = $varnt->getText();
648 * returns language specific hash options
652 function getExtraHashOptions() {
653 $variant = $this->getPreferredVariant();
654 return '!' . $variant ;
658 * get title text as defined in the body of the article text
662 function getParsedTitle() {
663 return $this->mTitleDisplay
;
667 * Load default conversion tables
668 * This method must be implemented in derived class
672 function loadDefaultTables() {
673 $name = get_class($this);
674 wfDie("Must implement loadDefaultTables() method in class $name");
678 * load conversion tables either from the cache or the disk
681 function loadTables($fromcache=true) {
683 if( $this->mTablesLoaded
)
685 wfProfileIn( __METHOD__
);
686 $this->mTablesLoaded
= true;
687 $this->mTables
= false;
689 wfProfileIn( __METHOD__
.'-cache' );
690 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
691 wfProfileOut( __METHOD__
.'-cache' );
693 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
694 wfProfileIn( __METHOD__
.'-recache' );
695 // not in cache, or we need a fresh reload.
696 // we will first load the default tables
697 // then update them using things in MediaWiki:Zhconversiontable/*
698 $this->loadDefaultTables();
699 foreach($this->mVariants
as $var) {
700 $cached = $this->parseCachedTable($var);
701 $this->mTables
[$var]->mergeArray($cached);
704 $this->postLoadTables();
705 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
707 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
708 wfProfileOut( __METHOD__
.'-recache' );
710 wfProfileOut( __METHOD__
);
714 * Hook for post processig after conversion tables are loaded
717 function postLoadTables() {}
720 * Reload the conversion tables
724 function reloadTables() {
726 unset($this->mTables
);
727 $this->mTablesLoaded
= false;
728 $this->loadTables(false);
733 * parse the conversion table stored in the cache
735 * the tables should be in blocks of the following form:
742 * to make the tables more manageable, subpages are allowed
743 * and will be parsed recursively if $recursive=true
746 function parseCachedTable($code, $subpage='', $recursive=true) {
747 global $wgMessageCache;
748 static $parsed = array();
750 if(!is_object($wgMessageCache))
753 $key = 'Conversiontable/'.$code;
755 $key .= '/' . $subpage;
757 if(array_key_exists($key, $parsed))
760 if ( strpos( $code, '/' ) === false ) {
761 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
763 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "Conversiontable/$code" );
764 if ( $title && $title->exists() ) {
765 $article = new Article( $title );
766 $txt = $article->getContents();
772 // get all subpage links of the form
773 // [[MediaWiki:conversiontable/zh-xx/...|...]]
774 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
775 $subs = explode('[[', $txt);
777 foreach( $subs as $sub ) {
778 $link = explode(']]', $sub, 2);
779 if(count($link) != 2)
781 $b = explode('|', $link[0]);
782 $b = explode('/', trim($b[0]), 3);
788 if($b[0] == $linkhead && $b[1] == $code) {
789 $sublinks[] = $sublink;
794 // parse the mappings in this page
795 $blocks = explode($this->mMarkup
['begin'], $txt);
796 array_shift($blocks);
798 foreach($blocks as $block) {
799 $mappings = explode($this->mMarkup
['end'], $block, 2);
800 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
801 $table = explode( ';', $stripped );
802 foreach( $table as $t ) {
803 $m = explode( '=>', $t );
804 if( count( $m ) != 2)
806 // trim any trailling comments starting with '//'
807 $tt = explode('//', $m[1], 2);
808 $ret[trim($m[0])] = trim($tt[0]);
811 $parsed[$key] = true;
814 // recursively parse the subpages
816 foreach($sublinks as $link) {
817 $s = $this->parseCachedTable($code, $link, $recursive);
818 $ret = array_merge($ret, $s);
822 if ($this->mUcfirst
) {
823 foreach ($ret as $k => $v) {
824 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
831 * Enclose a string with the "no conversion" tag. This is used by
832 * various functions in the Parser
834 * @param string $text text to be tagged for no conversion
835 * @return string the tagged text
838 function markNoConversion($text, $noParse=false) {
839 # don't mark if already marked
840 if(strpos($text, $this->mMarkup
['begin']) ||
841 strpos($text, $this->mMarkup
['end']))
844 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
849 * convert the sorting key for category links. this should make different
850 * keys that are variants of each other map to the same key
852 function convertCategoryKey( $key ) {
856 * hook to refresh the cache of conversion tables when
857 * MediaWiki:conversiontable* is updated
860 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
861 $titleobj = $article->getTitle();
862 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
863 $title = $titleobj->getDBkey();
864 $t = explode('/', $title, 3);
866 if( $c > 1 && $t[0] == 'Conversiontable' ) {
867 if(in_array($t[1], $this->mVariants
)) {
868 $this->reloadTables();
876 * Armour rendered math against conversion
877 * Wrap math into rawoutput -{R| math }- syntax
880 function armourMath($text){
881 // we need to convert '-{' and '}-' to '-{' and '}-'
882 // to avoid a unwanted '}-' appeared after the math-image.
883 $text = strtr( $text, array('-{' => '-{', '}-' => '}-') );
884 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
890 * parser for rules of language conversion , parse rules in -{ }- tag
892 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
894 class ConverterRule
{
895 var $mText; // original text in -{text}-
896 var $mConverter; // LanguageConverter object
897 var $mManualCodeError = '<strong class="error">code error!</strong>';
898 var $mRuleDisplay = '';
899 var $mRuleTitle = false;
900 var $mRules = '';// string : the text of the rules
901 var $mRulesAction = 'none';
902 var $mFlags = array();
903 var $mConvTable = array();
904 var $mBidtable = array();// array of the translation in each variant
905 var $mUnidtable = array();// array of the translation in each variant
910 * @param string $text the text between -{ and }-
911 * @param object $converter a LanguageConverter object
914 function __construct( $text, $converter ){
915 $this->mText
= $text;
916 $this->mConverter
= $converter;
917 foreach( $converter->mVariants
as $v ){
918 $this->mConvTable
[$v] = array();
923 * check if variants array in convert array
925 * @param string $variant Variant language code
926 * @return string Translated text
929 function getTextInBidtable( $variants ){
930 if( is_string( $variants ) ){ $variants = array( $variants ); }
931 if( !is_array( $variants ) ) return false;
932 foreach( $variants as $variant ){
933 if( array_key_exists( $variant, $this->mBidtable
) ){
934 return $this->mBidtable
[$variant];
941 * Parse flags with syntax -{FLAG| ... }-
944 function parseFlags(){
945 $text = $this->mText
;
946 if(strlen($text) < 2 ) {
947 $this->mFlags
= array( 'R' );
948 $this->mRules
= $text;
953 $markup = $this->mConverter
->mMarkup
;
954 $validFlags = $this->mConverter
->mFlags
;
955 $variants = $this->mConverter
->mVariants
;
957 $tt = explode($markup['flagsep'], $text, 2);
958 if(count($tt) == 2) {
959 $f = explode($markup['varsep'], $tt[0]);
962 if(array_key_exists($ff, $validFlags) &&
963 !in_array($validFlags[$ff], $flags))
964 $flags[] = $validFlags[$ff];
972 if( in_array('R',$flags) ){
973 $flags = array('R');// remove other flags
974 } elseif ( in_array('N',$flags) ){
975 $flags = array('N');// remove other flags
976 } elseif ( in_array('-',$flags) ){
977 $flags = array('-');// remove other flags
978 } elseif (count($flags)==1 && $flags[0]=='T'){
980 } elseif ( in_array('H',$flags) ){
981 // replace A flag, and remove other flags except T
982 $temp=array('+','H');
983 if(in_array('T',$flags)) $temp[] = 'T';
984 if(in_array('D',$flags)) $temp[] = 'D';
987 if ( in_array('A',$flags) ) {
991 if ( in_array('D',$flags) )
992 $flags=array_diff($flags,array('S'));
993 $flags_temp = array();
994 foreach ($variants as $variant) {
995 // try to find flags like "zh-hans", "zh-hant"
996 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
997 if ( in_array($variant, $flags) )
998 $flags_temp[] = $variant;
1000 if ( count($flags_temp) !== 0 )
1001 $flags = $flags_temp;
1003 if ( count($flags) == 0 )
1004 $flags = array('S');
1005 $this->mRules
=$rules;
1006 $this->mFlags
=$flags;
1010 * generate conversion table
1013 function parseRules() {
1014 $rules = $this->mRules
;
1015 $flags = $this->mFlags
;
1016 $bidtable = array();
1017 $unidtable = array();
1018 $markup = $this->mConverter
->mMarkup
;
1019 $variants = $this->mConverter
->mVariants
;
1021 // varsep_pattern for preg_split:
1022 // text should be splited by ";" only if a valid variant
1023 // name exist after the markup, for example:
1024 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
1025 // we should split it as:
1027 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1028 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1031 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1032 foreach( $variants as $variant ) {
1033 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
1034 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1035 . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1037 $varsep_pattern .= '\s*$)/';
1039 $choice = preg_split($varsep_pattern, $rules);
1041 foreach( $choice as $c ) {
1042 $v = explode($markup['codesep'], $c, 2);
1043 if( count($v) != 2 )
1044 continue;// syntax error, skip
1047 $u = explode($markup['unidsep'], $v, 2);
1048 // if $to is empty, strtr() could return a wrong result
1049 if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
1050 $bidtable[$v] = $to;
1051 } else if(count($u) == 2){
1052 $from = trim($u[0]);
1054 if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
1055 && $to && in_array( $v, $variants ) )
1056 $unidtable[$v] = array( $from=>$to );
1057 elseif ( $to && in_array( $v, $variants ) )
1058 $unidtable[$v][$from] = $to;
1060 // syntax error, pass
1061 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ){
1062 $bidtable = array();
1063 $unidtable = array();
1067 $this->mBidtable
= $bidtable;
1068 $this->mUnidtable
= $unidtable;
1074 function getRulesDesc(){
1075 $codesep = $this->mConverter
->mDescCodeSep
;
1076 $varsep = $this->mConverter
->mDescVarSep
;
1078 foreach($this->mBidtable
as $k => $v)
1079 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
1080 foreach($this->mUnidtable
as $k => $a)
1081 foreach($a as $from=>$to)
1082 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
1087 * Parse rules conversion
1090 function getRuleConvertedStr( $variant, $doConvert ){
1091 $bidtable = $this->mBidtable
;
1092 $unidtable = $this->mUnidtable
;
1094 if( count($bidtable) +
count($unidtable) == 0 ){
1095 return $this->mRules
;
1096 } elseif ( $doConvert ){// the text converted
1097 // display current variant in bidirectional array
1098 $disp = $this->getTextInBidtable($variant);
1099 // or display current variant in fallbacks
1101 $disp = $this->getTextInBidtable(
1102 $this->mConverter
->getVariantFallbacks($variant));
1103 // or display current variant in unidirectional array
1104 if(!$disp && array_key_exists($variant,$unidtable)){
1105 $disp = array_values($unidtable[$variant]);
1108 // or display frist text under disable manual convert
1109 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
1110 if(count($bidtable)>0){
1111 $disp = array_values($bidtable);
1114 $disp = array_values($unidtable);
1115 $disp = array_values($disp[0]);
1120 } else {// no convert
1121 return $this->mRules
;
1126 * generate conversion table for all text
1129 function generateConvTable(){
1130 $flags = $this->mFlags
;
1131 $bidtable = $this->mBidtable
;
1132 $unidtable = $this->mUnidtable
;
1133 $manLevel = $this->mConverter
->mManualLevel
;
1136 foreach($this->mConverter
->mVariants
as $v) {
1137 /* for bidirectional array
1138 fill in the missing variants, if any,
1140 if(!array_key_exists($v, $bidtable)) {
1141 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
1142 $vf = $this->getTextInBidtable($variantFallbacks);
1143 if($vf) $bidtable[$v] = $vf;
1146 if(array_key_exists($v,$bidtable)){
1147 foreach($vmarked as $vo){
1148 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1149 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1150 // to introduce a custom mapping between
1151 // words WordZh and WordTw in the whole text
1152 if($manLevel[$v]=='bidirectional'){
1153 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1155 if($manLevel[$vo]=='bidirectional'){
1156 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1161 /*for unidirectional array
1162 fill to convert tables */
1163 $allow_unid = $manLevel[$v]=='bidirectional'
1164 ||
$manLevel[$v]=='unidirectional';
1165 if( $allow_unid && array_key_exists( $v, $unidtable ) ){
1166 $ct = $this->mConvTable
[$v];
1167 $this->mConvTable
[$v] = array_merge($ct, $unidtable[$v]);
1173 * Parse rules and flags
1176 function parse($variant){
1178 $variant = $this->mConverter
->getPreferredVariant();
1180 $variants = $this->mConverter
->mVariants
;
1181 $this->parseFlags();
1182 $flags = $this->mFlags
;
1184 // convert to specified variant
1185 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1186 if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
1187 if ( in_array( $variant, $flags ) ) // check if current variant in flags
1188 // then convert <text to convert> to current language
1189 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variant );
1190 else { // if current variant no in flags,
1191 // then we check its fallback variants.
1192 $variantFallbacks = $this->mConverter
->getVariantFallbacks($variant);
1193 foreach ( $variantFallbacks as $variantFallback ) {
1194 // if current variant's fallback exist in flags
1195 if ( in_array( $variantFallback, $flags ) ) {
1196 // then convert <text to convert> to fallback language
1197 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variantFallback );
1202 $this->mFlags
= $flags = array('R');
1205 if( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1206 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1207 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1209 $this->parseRules();
1211 $rules = $this->mRules
;
1213 if( count( $this->mBidtable
) == 0 && count( $this->mUnidtable
) == 0 ){
1214 if(in_array('+',$flags) ||
in_array('-',$flags))
1215 // fill all variants if text in -{A/H/-|text} without rules
1216 foreach($this->mConverter
->mVariants
as $v)
1217 $this->mBidtable
[$v] = $rules;
1218 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1219 $this->mFlags
= $flags = array('R');
1222 if( in_array('R',$flags) ) {
1223 // if we don't do content convert, still strip the -{}- tags
1224 $this->mRuleDisplay
= $rules;
1225 } elseif ( in_array('N',$flags) ){
1226 // proces N flag: output current variant name
1227 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1228 } elseif ( in_array('D',$flags) ){
1229 // proces D flag: output rules description
1230 $this->mRuleDisplay
= $this->getRulesDesc();
1231 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1232 // proces H,- flag or T only: output nothing
1233 $this->mRuleDisplay
= '';
1234 } elseif ( in_array('S',$flags) ){
1235 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1236 $this->mConverter
->mDoContentConvert
);
1238 $this->mRuleDisplay
= $this->mManualCodeError
;
1241 if ( in_array('T',$flags) ) {
1242 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1243 $this->mConverter
->mDoTitleConvert
);
1246 if (in_array('-', $flags))
1247 $this->mRulesAction
='remove';
1248 if (in_array('+', $flags))
1249 $this->mRulesAction
='add';
1251 $this->generateConvTable();
1257 function hasRules(){
1262 * get display text on markup -{...}-
1265 function getDisplay(){
1266 return $this->mRuleDisplay
;
1269 * get converted title
1272 function getTitle(){
1273 return $this->mRuleTitle
;
1277 * return how deal with conversion rules
1280 function getRulesAction(){
1281 return $this->mRulesAction
;
1285 * get conversion table ( bidirectional and unidirectional conversion table )
1288 function getConvTable(){
1289 return $this->mConvTable
;
1293 * get conversion rules string
1296 function getRules(){
1297 return $this->mRules
;
1301 * get conversion flags
1304 function getFlags(){
1305 return $this->mFlags
;