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 $mManualAddTables;
25 var $mManualRemoveTables;
26 var $mNamespaceTables;
27 var $mTitleDisplay='';
28 var $mDoTitleConvert=true, $mDoContentConvert=true;
29 var $mManualLevel; // 'bidirectional' 'unidirectional' 'disable' for each variants
30 var $mTitleFromFlag = false;
35 var $mDescCodeSep = ':',$mDescVarSep = ';';
36 var $mUcfirst = false;
37 var $mGroups = array();
39 const CACHE_VERSION_KEY
= 'VERSION 6';
44 * @param string $maincode the main language code of this language
45 * @param array $variants the supported variants of this language
46 * @param array $variantfallback the fallback language of each variant
47 * @param array $markup array defining the markup used for manual conversion
48 * @param array $flags array defining the custom strings that maps to the flags
49 * @param array $manualLevel limit for supported variants
52 function __construct($langobj, $maincode,
54 $variantfallbacks=array(),
57 $manualLevel = array() ) {
58 $this->mLangObj
= $langobj;
59 $this->mMainLanguageCode
= $maincode;
60 $this->mVariants
= $variants;
61 $this->mVariantFallbacks
= $variantfallbacks;
62 global $wgLanguageNames;
63 $this->mVariantNames
= $wgLanguageNames;
64 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
68 'unidsep'=>'=>', //for unidirectional conversion
73 $this->mMarkup
= array_merge($m, $markup);
75 // 'S' show converted text
76 // '+' add rules for alltext
77 // 'E' the gave flags is error
78 // these flags above are reserved for program
79 'A'=>'A', // add rule for convert code (all text convert)
80 'T'=>'T', // title convert
81 'R'=>'R', // raw content
82 'D'=>'D', // convert description (subclass implement)
83 '-'=>'-', // remove convert (not implement)
84 'H'=>'H', // add rule for convert code (but no display in placed code )
85 'N'=>'N' // current variant name
87 $this->mFlags
= array_merge($f, $flags);
88 foreach( $this->mVariants
as $v) {
89 $this->mManualLevel
[$v]=array_key_exists($v,$manualLevel)
92 $this->mManualAddTables
[$v] = array();
93 $this->mManualRemoveTables
[$v] = array();
94 $this->mNamespaceTables
[$v] = array();
95 $this->mFlags
[$v] = $v;
102 function getVariants() {
103 return $this->mVariants
;
107 * in case some variant is not defined in the markup, we need
108 * to have some fallback. for example, in zh, normally people
109 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
110 * when zh-sg is preferred but not defined, we will pick zh-hans
111 * in this case. right now this is only used by zh.
113 * @param string $v the language code of the variant
114 * @return string array the code of the fallback language or false if there is no fallback
117 function getVariantFallbacks($v) {
118 if( isset( $this->mVariantFallbacks
[$v] ) ) {
119 return $this->mVariantFallbacks
[$v];
121 return $this->mMainLanguageCode
;
125 * get preferred language variants.
126 * @param boolean $fromUser Get it from $wgUser's preferences
127 * @return string the preferred language code
130 function getPreferredVariant( $fromUser = true ) {
131 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
133 if($this->mPreferredVariant
)
134 return $this->mPreferredVariant
;
136 // figure out user lang without constructing wgLang to avoid infinite recursion
138 $defaultUserLang = $wgUser->getOption( 'language' );
140 $defaultUserLang = $this->mMainLanguageCode
;
141 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
142 // see if interface language is same as content, if not, prevent conversion
143 if( ! in_array( $userLang, $this->mVariants
) ){
144 $this->mPreferredVariant
= $this->mMainLanguageCode
; // no conversion
145 return $this->mPreferredVariant
;
148 // see if the preference is set in the request
149 $req = $wgRequest->getText( 'variant' );
150 if( in_array( $req, $this->mVariants
) ) {
151 $this->mPreferredVariant
= $req;
155 // check the syntax /code/ArticleTitle
156 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
157 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
158 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
159 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
160 if(in_array($scriptBase,$this->mVariants
)){
161 $this->mPreferredVariant
= $scriptBase;
162 return $this->mPreferredVariant
;
166 // get language variant preference from logged in users
167 // Don't call this on stub objects because that causes infinite
168 // recursion during initialisation
169 if( $fromUser && $wgUser->isLoggedIn() ) {
170 $this->mPreferredVariant
= $wgUser->getOption('variant');
171 return $this->mPreferredVariant
;
174 // see if default variant is globaly set
175 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
176 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
177 return $this->mPreferredVariant
;
180 if( !$this->mPreferredVariant
) {
181 // see if some supported language variant is set in the
182 // http header, but we don't set the mPreferredVariant
183 // variable in case this is called before the user's
184 // preference is loaded
185 if( array_key_exists( 'HTTP_ACCEPT_LANGUAGE', $_SERVER ) ) {
186 $acceptLanguage = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
188 // take the part of the string up to the first semicolon
189 if($semiPos = strpos( $acceptLanguage, ';' ) !== false )
190 $acceptLanguage = substr( $acceptLanguage, 0, $semiPos );
193 $languages = explode(',', $acceptLanguage);
195 foreach( $languages as $language ) {
197 $language = trim( $language );
198 if( in_array( $language, $this->mVariants
) ) {
206 return $this->mMainLanguageCode
;
211 * caption convert, base on preg_replace_callback
213 * to convert text in "title" or "alt", like '<img alt="text" ... '
214 * or '<span title="text" ... '
216 * @return string like ' alt="yyyy"' or ' title="yyyy"'
219 function captionConvert( $matches ) {
220 $toVariant = $this->getPreferredVariant();
221 $title = $matches[1];
223 // we convert captions except URL
224 if( !strpos( $text, '://' ) )
225 $text = $this->translate($text, $toVariant);
226 return " $title=\"$text\"";
230 * dictionary-based conversion
232 * @param string $text the text to be converted
233 * @param string $toVariant the target language code
234 * @return string the converted text
237 function autoConvert($text, $toVariant=false) {
238 $fname="LanguageConverter::autoConvert";
240 wfProfileIn( $fname );
242 if(!$this->mTablesLoaded
)
246 $toVariant = $this->getPreferredVariant();
247 if(!in_array($toVariant, $this->mVariants
))
250 /* we convert everything except:
251 1. html markups (anything between < and >)
253 3. place holders created by the parser
256 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
257 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
261 // this one is needed when the text is inside an html markup
262 $htmlfix = '|<[^>]+$|^[^<>]*>';
264 // disable convert to variants between <code></code> tags
265 $codefix = '<code>.+?<\/code>|';
266 // disable convertsion of <script type="text/javascript"> ... </script>
267 $scriptfix = '<script.*?>.*?<\/script>|';
268 // disable conversion of <pre xxxx> ... </pre>
269 $prefix = '<pre.*?>.*?<\/pre>|';
271 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
273 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
275 $m = array_shift($matches);
277 $ret = $this->translate($m[0], $toVariant);
278 $mstart = $m[1]+
strlen($m[0]);
280 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
281 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
282 foreach($matches as $m) {
283 $mark = substr($text, $mstart, $m[1]-$mstart);
284 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
286 $ret .= $this->translate($m[0], $toVariant);
287 $mstart = $m[1] +
strlen($m[0]);
289 wfProfileOut( $fname );
294 * Translate a string to a variant
295 * Doesn't process markup or do any of that other stuff, for that use convert()
297 * @param string $text Text to convert
298 * @param string $variant Variant language code
299 * @return string Translated text
302 function translate( $text, $variant ) {
303 wfProfileIn( __METHOD__
);
304 if( !$this->mTablesLoaded
)
306 $text = $this->mTables
[$variant]->replace( $text );
307 wfProfileOut( __METHOD__
);
312 * convert text to all supported variants
314 * @param string $text the text to be converted
315 * @return array of string
318 function autoConvertToAllVariants($text) {
319 $fname="LanguageConverter::autoConvertToAllVariants";
320 wfProfileIn( $fname );
321 if( !$this->mTablesLoaded
)
325 foreach($this->mVariants
as $variant) {
326 $ret[$variant] = $this->translate($text, $variant);
329 wfProfileOut( $fname );
334 * convert link text to all supported variants
336 * @param string $text the text to be converted
337 * @return array of string
340 function convertLinkToAllVariants($text) {
341 if( !$this->mTablesLoaded
)
345 $tarray = explode($this->mMarkup
['begin'], $text);
346 $tfirst = array_shift($tarray);
348 foreach($this->mVariants
as $variant)
349 $ret[$variant] = $this->translate($tfirst,$variant);
351 foreach($tarray as $txt) {
352 $marked = explode($this->mMarkup
['end'], $txt, 2);
354 foreach($this->mVariants
as $variant){
355 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
356 if(array_key_exists(1, $marked))
357 $ret[$variant] .= $this->translate($marked[1],$variant);
366 * prepare manual conversion table
369 function prepareManualConv( $convRule ){
370 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
371 $title = $convRule->getTitle();
373 $this->mTitleFromFlag
= true;
374 $this->mTitleDisplay
= $title;
377 //apply manual conversion table to global table
378 $convTable = $convRule->getConvTable();
379 $action = $convRule->getRulesAction();
380 foreach( $convTable as $v => $t ) {
381 if( !in_array( $v, $this->mVariants
) )continue;
382 if( $action=="add" ) {
383 foreach( $t as $from => $to ) {
384 // to ensure that $from and $to not be left blank
385 // so $this->translate() could always return a string
387 // more efficient than array_merge(), about 2.5 times.
388 $this->mManualAddTables
[$v][$from] = $to;
391 elseif ( $action == "remove" ) {
392 foreach ( $t as $from=>$to ) {
394 $this->mManualRemoveTables
[$v][$from] = $to;
401 * apply manual conversion from $this->mManualAddTables and $this->mManualRemoveTables
404 function applyManualConv(){
405 //apply manual conversion table to global table
406 foreach($this->mVariants
as $v) {
407 if (count($this->mManualAddTables
[$v]) > 0) {
408 $this->mTables
[$v]->mergeArray($this->mManualAddTables
[$v]);
410 if (count($this->mManualRemoveTables
[$v]) > 0)
411 $this->mTables
[$v]->removeArray($this->mManualRemoveTables
[$v]);
416 * Convert text using a parser object for context
419 function parserConvert( $text, &$parser ) {
420 global $wgDisableLangConversion;
421 /* don't do anything if this is the conversion table */
422 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
423 strpos($parser->mTitle
->getText(), 'onversiontable') !== false )
428 if ( $wgDisableLangConversion )
431 $text = $this->convert( $text );
433 if ( $this->mTitleFromFlag
)
434 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
440 * @param string $title the title included namespace
441 * @return array of string
444 function convertNamespace( $title, $variant ) {
445 $splittitle = explode( ':', $title );
446 if (count($splittitle) < 2)
448 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) )
449 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
450 $ret = implode(':', $splittitle );
458 function convertTitle( $text, $variant ){
459 global $wgDisableTitleConversion, $wgUser;
461 // check for global param and __NOTC__ tag
462 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
$wgUser->getOption('noconvertlink') == 1 ) {
463 $this->mTitleDisplay
= $text;
467 // use the title from the T flag if any
468 if( $this->mTitleFromFlag
){
469 $this->mTitleFromFlag
= false;
470 return $this->mTitleDisplay
;
474 $isredir = $wgRequest->getText( 'redirect', 'yes' );
475 $action = $wgRequest->getText( 'action' );
476 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
477 if ( $isredir == 'no' ||
$action == 'edit' ||
$action == 'submit' ||
$linkconvert == 'no' ) {
480 $text = $this->convertNamespace( $text, $variant );
481 $this->mTitleDisplay
= $this->convert( $text );
482 return $this->mTitleDisplay
;
487 * convert text to different variants of a language. the automatic
488 * conversion is done in autoConvert(). here we parse the text
489 * marked with -{}-, which specifies special conversions of the
490 * text that can not be accomplished in autoConvert()
492 * syntax of the markup:
493 * -{code1:text1;code2:text2;...}- or
494 * -{flags|code1:text1;code2:text2;...}- or
495 * -{text}- in which case no conversion should take place for text
497 * @param string $text text to be converted
498 * @param bool $isTitle whether this conversion is for the article title
499 * @param string $variant the variant we convert to
500 * @return string converted text
503 function convert( $text, $isTitle = false, $variant = null ) {
505 $mw =& MagicWord
::get( 'notitleconvert' );
506 if( $mw->matchAndRemove( $text ) )
507 $this->mDoTitleConvert
= false;
508 $mw =& MagicWord
::get( 'nocontentconvert' );
509 if( $mw->matchAndRemove( $text ) ) {
510 $this->mDoContentConvert
= false;
513 // no conversion if redirecting
514 $mw =& MagicWord
::get( 'redirect' );
515 if( $mw->matchStart( $text ) )
518 if( $variant && in_array( $variant, $this->mVariants
) )
521 $plang = $this->getPreferredVariant();
523 // for title convertion
524 if ( $isTitle ) return $this->convertTitle( $text, $plang );
526 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
530 foreach ( $tarray as $txt ) {
531 $marked = explode( $this->mMarkup
['begin'], $txt, 2 );
532 if ( array_key_exists( 1, $marked ) ) {
533 $crule = new ConverterRule($marked[1], $this);
534 $crule->parse( $plang );
535 $marked[1] = $crule->getDisplay();
536 $this->prepareManualConv( $crule );
539 $marked[0] .= $this->mMarkup
['end'];
540 array_push( $marks, $marked );
542 $this->applyManualConv();
543 foreach ( $marks as $marked ) {
544 if( $this->mDoContentConvert
)
545 $text .= $this->autoConvert( $marked[0], $plang );
548 if( array_key_exists( 1, $marked ) )
551 // Remove the last delimiter (wasn't real)
552 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
558 * if a language supports multiple variants, it is
559 * possible that non-existing link in one variant
560 * actually exists in another variant. this function
561 * tries to find it. See e.g. LanguageZh.php
563 * @param string $link the name of the link
564 * @param mixed $nt the title object of the link
565 * @param boolean $ignoreOtherCond: to disable other conditions when
566 * we need to transclude a template or update a category's link
567 * @return null the input parameters may be modified upon return
570 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
571 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
572 $isredir = $wgRequest->getText( 'redirect', 'yes' );
573 $action = $wgRequest->getText( 'action' );
574 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
575 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
576 $linkBatch = new LinkBatch();
580 if ( $disableLinkConversion ||
( !$ignoreOtherCond && ( $isredir == 'no' ||
$action == 'edit'
581 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) )
585 $ns = $nt->getNamespace();
587 $variants = $this->autoConvertToAllVariants($link);
588 if($variants == false) //give up
593 foreach( $variants as $v ) {
595 $varnt = Title
::newFromText( $v, $ns );
596 if(!is_null($varnt)){
597 $linkBatch->addObj($varnt);
603 // fetch all variants in single query
604 $linkBatch->execute();
606 foreach( $titles as $varnt ) {
607 if( $varnt->getArticleID() > 0 ) {
609 $link = $varnt->getText();
616 * returns language specific hash options
620 function getExtraHashOptions() {
621 $variant = $this->getPreferredVariant();
622 return '!' . $variant ;
626 * get title text as defined in the body of the article text
630 function getParsedTitle() {
631 return $this->mTitleDisplay
;
635 * a write lock to the cache
639 function lockCache() {
642 for($i=0; $i<30; $i++
) {
643 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
655 function unlockCache() {
657 $wgMemc->delete($this->mCacheKey
. "lock");
662 * Load default conversion tables
663 * This method must be implemented in derived class
667 function loadDefaultTables() {
668 $name = get_class($this);
669 wfDie("Must implement loadDefaultTables() method in class $name");
673 * load conversion tables either from the cache or the disk
676 function loadTables( $fromcache = true ) {
678 if( $this->mTablesLoaded
)
680 wfProfileIn( __METHOD__
);
681 $this->mTablesLoaded
= true;
682 $this->mTables
= false;
684 wfProfileIn( __METHOD__
.'-cache' );
685 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
686 wfProfileOut( __METHOD__
.'-cache' );
688 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
689 wfProfileIn( __METHOD__
.'-recache' );
690 // not in cache, or we need a fresh reload.
691 // we will first load the default tables
692 // then update them using things in MediaWiki:Zhconversiontable/*
693 $this->loadDefaultTables();
694 foreach( $this->mVariants
as $var ) {
695 $cached = $this->parseCachedTable( $var );
696 // load group convert table, e.g. [[MediaWiki:Groupconversiontable-StarTrek]].
697 foreach( $this->mGroups
as $group ) {
698 $cachedgroup = $this->parseCachedTable( $var, '', true, "Groupconversiontable-$group" );
699 $cached = array_merge( $cached, $cachedgroup );
701 $this->mTables
[$var]->mergeArray( $cached );
704 $this->postLoadTables();
705 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
707 if($this->lockCache()) {
708 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
709 $this->unlockCache();
711 wfProfileOut( __METHOD__
.'-recache' );
713 wfProfileOut( __METHOD__
);
717 * Hook for post processig after conversion tables are loaded
720 function postLoadTables() {}
723 * Reload the conversion tables
727 function reloadTables() {
729 unset($this->mTables
);
730 $this->mTablesLoaded
= false;
731 $this->loadTables(false);
736 * parse the conversion table stored in the cache
738 * the tables should be in blocks of the following form:
745 * to make the tables more manageable, subpages are allowed
746 * and will be parsed recursively if $recursive=true
749 function parseCachedTable($code, $subpage='', $recursive=true, $table='Conversiontable') {
750 global $wgMessageCache;
751 static $parsed = array();
753 if(!is_object($wgMessageCache))
756 $key = "$table/".$code;
758 $key .= '/' . $subpage;
760 if(array_key_exists($key, $parsed))
763 if ( strpos( $code, '/' ) === false ) {
764 $txt = $wgMessageCache->get( $table, true, $code );
766 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "$table/$code" );
767 if ( $title && $title->exists() ) {
768 $article = new Article( $title );
769 $txt = $article->getContents();
774 // get all subpage links of the form
775 // [[MediaWiki:conversiontable/zh-xx/...|...]]
776 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ":$table";
777 $subs = explode('[[', $txt);
779 foreach( $subs as $sub ) {
780 $link = explode(']]', $sub, 2);
781 if(count($link) != 2)
783 $b = explode('|', $link[0]);
784 $b = explode('/', trim($b[0]), 3);
790 if($b[0] == $linkhead && $b[1] == $code) {
791 $sublinks[] = $sublink;
795 // parse the mappings in this page
796 $blocks = explode($this->mMarkup
['begin'], $txt);
797 array_shift($blocks);
799 foreach($blocks as $block) {
800 $mappings = explode($this->mMarkup
['end'], $block, 2);
801 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
802 $table = explode( ';', $stripped );
803 foreach( $table as $t ) {
804 $m = explode( '=>', $t );
805 if( count( $m ) != 2)
807 // trim any trailling comments starting with '//'
808 $tt = explode('//', $m[1], 2);
809 $ret[trim($m[0])] = trim($tt[0]);
812 $parsed[$key] = true;
815 // recursively parse the subpages
817 foreach($sublinks as $link) {
818 $s = $this->parseCachedTable($code, $link, $recursive);
819 $ret = array_merge($ret, $s);
823 if ($this->mUcfirst
) {
824 foreach ($ret as $k => $v) {
825 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
832 * Enclose a string with the "no conversion" tag. This is used by
833 * various functions in the Parser
835 * @param string $text text to be tagged for no conversion
836 * @return string the tagged text
839 function markNoConversion($text, $noParse=false) {
840 # don't mark if already marked
841 if(strpos($text, $this->mMarkup
['begin']) ||
842 strpos($text, $this->mMarkup
['end']))
845 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
850 * convert the sorting key for category links. this should make different
851 * keys that are variants of each other map to the same key
853 function convertCategoryKey( $key ) {
857 * hook to refresh the cache of conversion tables when
858 * MediaWiki:conversiontable* is updated
861 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
862 $titleobj = $article->getTitle();
863 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
864 $title = $titleobj->getDBkey();
865 $t = explode('/', $title, 3);
867 if( $c > 1 && $t[0] == 'Conversiontable' ) {
868 if(in_array($t[1], $this->mVariants
)) {
869 $this->reloadTables();
877 * Armour rendered math against conversion
878 * Wrap math into rawoutput -{R| math }- syntax
881 function armourMath($text){
882 // we need to convert '-{' and '}-' to '-{' and '}-'
883 // to avoid a unwanted '}-' appeared after the math-image.
884 $text = strtr( $text, array('-{' => '-{', '}-' => '}-') );
885 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
890 * Callback function for magicword 'groupconvert'
892 * @param string $group: the group name called for
893 * @return blank string
895 function groupConvert( $group ) {
896 $this->mGroups
[] = $group;
902 * parser for rules of language conversion , parse rules in -{ }- tag
904 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
906 class ConverterRule
{
907 var $mText; // original text in -{text}-
908 var $mConverter; // LanguageConverter object
909 var $mManualCodeError='<strong class="error">code error!</strong>';
910 var $mRuleDisplay = '',$mRuleTitle=false;
911 var $mRules = '';// string : the text of the rules
912 var $mRulesAction = 'none';
913 var $mFlags = array();
914 var $mConvTable = array();
915 var $mBidtable = array();// array of the translation in each variant
916 var $mUnidtable = array();// array of the translation in each variant
921 * @param string $text the text between -{ and }-
922 * @param object $converter a LanguageConverter object
925 function __construct($text,$converter){
926 $this->mText
= $text;
927 $this->mConverter
=$converter;
928 foreach($converter->mVariants
as $v){
929 $this->mConvTable
[$v]=array();
934 * check if variants array in convert array
936 * @param string $variant Variant language code
937 * @return string Translated text
940 function getTextInBidtable($variants){
941 if(is_string($variants)){ $variants=array($variants); }
942 if(!is_array($variants)) return false;
943 foreach ($variants as $variant){
944 if(array_key_exists($variant, $this->mBidtable
)){
945 return $this->mBidtable
[$variant];
952 * Parse flags with syntax -{FLAG| ... }-
955 function parseFlags(){
956 $text = $this->mText
;
957 if(strlen($text) < 2 ) {
958 $this->mFlags
= array( 'R' );
959 $this->mRules
= $text;
964 $markup = $this->mConverter
->mMarkup
;
965 $validFlags = $this->mConverter
->mFlags
;
966 $variants = $this->mConverter
->mVariants
;
968 $tt = explode($markup['flagsep'], $text, 2);
969 if(count($tt) == 2) {
970 $f = explode($markup['varsep'], $tt[0]);
973 if(array_key_exists($ff, $validFlags) &&
974 !in_array($validFlags[$ff], $flags))
975 $flags[] = $validFlags[$ff];
983 if( in_array('R',$flags) ){
984 $flags = array('R');// remove other flags
985 } elseif ( in_array('N',$flags) ){
986 $flags = array('N');// remove other flags
987 } elseif ( in_array('-',$flags) ){
988 $flags = array('-');// remove other flags
989 } elseif (count($flags)==1 && $flags[0]=='T'){
991 } elseif ( in_array('H',$flags) ){
992 // replace A flag, and remove other flags except T
993 $temp=array('+','H');
994 if(in_array('T',$flags)) $temp[] = 'T';
995 if(in_array('D',$flags)) $temp[] = 'D';
998 if ( in_array('A',$flags) ) {
1002 if ( in_array('D',$flags) )
1003 $flags=array_diff($flags,array('S'));
1004 $flags_temp = array();
1005 foreach ($variants as $variant) {
1006 // try to find flags like "zh-hans", "zh-hant"
1007 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1008 if ( in_array($variant, $flags) )
1009 $flags_temp[] = $variant;
1011 if ( count($flags_temp) !== 0 )
1012 $flags = $flags_temp;
1014 if ( count($flags) == 0 )
1015 $flags = array('S');
1016 $this->mRules
=$rules;
1017 $this->mFlags
=$flags;
1021 * generate conversion table
1024 function parseRules() {
1025 $rules = $this->mRules
;
1026 $flags = $this->mFlags
;
1027 $bidtable = array();
1028 $unidtable = array();
1029 $markup = $this->mConverter
->mMarkup
;
1030 $variants = $this->mConverter
->mVariants
;
1032 // varsep_pattern for preg_split:
1033 // text should be splited by ";" only if a valid variant
1034 // name exist after the markup, for example:
1035 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
1036 // we should split it as:
1038 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1039 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1042 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1043 foreach( $variants as $variant ) {
1044 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
1045 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1046 . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1048 $varsep_pattern .= '\s*$)/';
1050 $choice = preg_split($varsep_pattern, $rules);
1052 foreach( $choice as $c ) {
1053 $v = explode($markup['codesep'], $c, 2);
1054 if( count($v) != 2 )
1055 continue;// syntax error, skip
1058 $u = explode($markup['unidsep'], $v);
1059 // if $to is empty, strtr() could return a wrong result
1060 if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
1061 $bidtable[$v] = $to;
1062 } else if(count($u) == 2){
1063 $from = trim($u[0]);
1065 if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
1066 && $to && in_array( $v, $variants ) )
1067 $unidtable[$v] = array( $from=>$to );
1068 elseif ( $to && in_array( $v, $variants ) )
1069 $unidtable[$v][$from] = $to;
1071 // syntax error, pass
1072 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ){
1073 $bidtable = array();
1074 $unidtable = array();
1078 $this->mBidtable
= $bidtable;
1079 $this->mUnidtable
= $unidtable;
1085 function getRulesDesc(){
1086 $codesep = $this->mConverter
->mDescCodeSep
;
1087 $varsep = $this->mConverter
->mDescVarSep
;
1089 foreach($this->mBidtable
as $k => $v)
1090 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
1091 foreach($this->mUnidtable
as $k => $a)
1092 foreach($a as $from=>$to)
1093 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
1098 * Parse rules conversion
1101 function getRuleConvertedStr($variant,$doConvert){
1102 $bidtable = $this->mBidtable
;
1103 $unidtable = $this->mUnidtable
;
1105 if( count($bidtable) +
count($unidtable) == 0 ){
1106 return $this->mRules
;
1107 } elseif ($doConvert){// the text converted
1108 // display current variant in bidirectional array
1109 $disp = $this->getTextInBidtable($variant);
1110 // or display current variant in fallbacks
1112 $disp = $this->getTextInBidtable(
1113 $this->mConverter
->getVariantFallbacks($variant));
1114 // or display current variant in unidirectional array
1115 if(!$disp && array_key_exists($variant,$unidtable)){
1116 $disp = array_values($unidtable[$variant]);
1119 // or display frist text under disable manual convert
1120 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
1121 if(count($bidtable)>0){
1122 $disp = array_values($bidtable);
1125 $disp = array_values($unidtable);
1126 $disp = array_values($disp[0]);
1131 } else {// no convert
1132 return $this->mRules
;
1137 * generate conversion table for all text
1140 function generateConvTable(){
1141 $flags = $this->mFlags
;
1142 $bidtable = $this->mBidtable
;
1143 $unidtable = $this->mUnidtable
;
1144 $manLevel = $this->mConverter
->mManualLevel
;
1147 foreach($this->mConverter
->mVariants
as $v) {
1148 /* for bidirectional array
1149 fill in the missing variants, if any,
1151 if(!array_key_exists($v, $bidtable)) {
1152 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
1153 $vf = $this->getTextInBidtable($variantFallbacks);
1154 if($vf) $bidtable[$v] = $vf;
1157 if(array_key_exists($v,$bidtable)){
1158 foreach($vmarked as $vo){
1159 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1160 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1161 // to introduce a custom mapping between
1162 // words WordZh and WordTw in the whole text
1163 if($manLevel[$v]=='bidirectional'){
1164 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1166 if($manLevel[$vo]=='bidirectional'){
1167 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1172 /*for unidirectional array
1173 fill to convert tables */
1174 $allow_unid = $manLevel[$v]=='bidirectional'
1175 ||
$manLevel[$v]=='unidirectional';
1176 if($allow_unid && array_key_exists($v,$unidtable)){
1177 $ct=$this->mConvTable
[$v];
1178 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1184 * Parse rules and flags
1187 function parse($variant){
1189 $variant = $this->mConverter
->getPreferredVariant();
1191 $variants = $this->mConverter
->mVariants
;
1192 $this->parseFlags();
1193 $flags = $this->mFlags
;
1195 // convert to specified variant
1196 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1197 if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
1198 if ( in_array( $variant, $flags ) ) // check if current variant in flags
1199 // then convert <text to convert> to current language
1200 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variant );
1201 else { // if current variant no in flags,
1202 // then we check its fallback variants.
1203 $variantFallbacks = $this->mConverter
->getVariantFallbacks($variant);
1204 foreach ( $variantFallbacks as $variantFallback ) {
1205 // if current variant's fallback exist in flags
1206 if ( in_array( $variantFallback, $flags ) ) {
1207 // then convert <text to convert> to fallback language
1208 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variantFallback );
1213 $this->mFlags
= $flags = array('R');
1216 if( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1217 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1218 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1220 $this->parseRules();
1222 $rules = $this->mRules
;
1224 if( count( $this->mBidtable
) == 0 && count( $this->mUnidtable
) == 0 ){
1225 if(in_array('+',$flags) ||
in_array('-',$flags))
1226 // fill all variants if text in -{A/H/-|text} without rules
1227 foreach($this->mConverter
->mVariants
as $v)
1228 $this->mBidtable
[$v] = $rules;
1229 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1230 $this->mFlags
= $flags = array('R');
1233 if( in_array('R',$flags) ) {
1234 // if we don't do content convert, still strip the -{}- tags
1235 $this->mRuleDisplay
= $rules;
1236 } elseif ( in_array('N',$flags) ){
1237 // proces N flag: output current variant name
1238 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1239 } elseif ( in_array('D',$flags) ){
1240 // proces D flag: output rules description
1241 $this->mRuleDisplay
= $this->getRulesDesc();
1242 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1243 // proces H,- flag or T only: output nothing
1244 $this->mRuleDisplay
= '';
1245 } elseif ( in_array('S',$flags) ){
1246 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1247 $this->mConverter
->mDoContentConvert
);
1249 $this->mRuleDisplay
= $this->mManualCodeError
;
1252 if ( in_array('T',$flags) ) {
1253 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1254 $this->mConverter
->mDoTitleConvert
);
1257 if (in_array('-', $flags))
1258 $this->mRulesAction
='remove';
1259 if (in_array('+', $flags))
1260 $this->mRulesAction
='add';
1262 $this->generateConvTable();
1268 function hasRules(){
1273 * get display text on markup -{...}-
1276 function getDisplay(){
1277 return $this->mRuleDisplay
;
1280 * get converted title
1283 function getTitle(){
1284 return $this->mRuleTitle
;
1288 * return how deal with conversion rules
1291 function getRulesAction(){
1292 return $this->mRulesAction
;
1296 * get conversion table ( bidirectional and unidirectional conversion table )
1299 function getConvTable(){
1300 return $this->mConvTable
;
1304 * get conversion rules string
1307 function getRules(){
1308 return $this->mRules
;
1312 * get conversion flags
1315 function getFlags(){
1316 return $this->mFlags
;