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 # FIXME rewrite code for parsing http header. The current code
181 # is written specific for detecting zh- variants
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 $pv=$this->mMainLanguageCode
;
188 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
189 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
190 $zh = strstr($header, $pv.'-');
192 $ary = split("[,;]",$zh);
196 // don't try to return bad variant
197 if(in_array( $pv, $this->mVariants
))
201 return $this->mMainLanguageCode
;
206 * caption convert, base on preg_replace_callback
208 * to convert text in "title" or "alt", like '<img alt="text" ... '
209 * or '<span title="text" ... '
211 * @return string like ' alt="yyyy"' or ' title="yyyy"'
214 function captionConvert( $matches ) {
215 $toVariant = $this->getPreferredVariant();
216 $title = $matches[1];
218 // we convert captions except URL
219 if( !strpos( $text, '://' ) )
220 $text = $this->translate($text, $toVariant);
221 return " $title=\"$text\"";
225 * dictionary-based conversion
227 * @param string $text the text to be converted
228 * @param string $toVariant the target language code
229 * @return string the converted text
232 function autoConvert($text, $toVariant=false) {
233 $fname="LanguageConverter::autoConvert";
235 wfProfileIn( $fname );
237 if(!$this->mTablesLoaded
)
241 $toVariant = $this->getPreferredVariant();
242 if(!in_array($toVariant, $this->mVariants
))
245 /* we convert everything except:
246 1. html markups (anything between < and >)
248 3. place holders created by the parser
251 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
252 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
256 // this one is needed when the text is inside an html markup
257 $htmlfix = '|<[^>]+$|^[^<>]*>';
259 // disable convert to variants between <code></code> tags
260 $codefix = '<code>.+?<\/code>|';
261 // disable convertsion of <script type="text/javascript"> ... </script>
262 $scriptfix = '<script.*?>.*?<\/script>|';
263 // disable conversion of <pre xxxx> ... </pre>
264 $prefix = '<pre.*?>.*?<\/pre>|';
266 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
268 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
270 $m = array_shift($matches);
272 $ret = $this->translate($m[0], $toVariant);
273 $mstart = $m[1]+
strlen($m[0]);
275 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
276 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
277 foreach($matches as $m) {
278 $mark = substr($text, $mstart, $m[1]-$mstart);
279 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
281 $ret .= $this->translate($m[0], $toVariant);
282 $mstart = $m[1] +
strlen($m[0]);
284 wfProfileOut( $fname );
289 * Translate a string to a variant
290 * Doesn't process markup or do any of that other stuff, for that use convert()
292 * @param string $text Text to convert
293 * @param string $variant Variant language code
294 * @return string Translated text
297 function translate( $text, $variant ) {
298 wfProfileIn( __METHOD__
);
299 if( !$this->mTablesLoaded
)
301 $text = $this->mTables
[$variant]->replace( $text );
302 wfProfileOut( __METHOD__
);
307 * convert text to all supported variants
309 * @param string $text the text to be converted
310 * @return array of string
313 function autoConvertToAllVariants($text) {
314 $fname="LanguageConverter::autoConvertToAllVariants";
315 wfProfileIn( $fname );
316 if( !$this->mTablesLoaded
)
320 foreach($this->mVariants
as $variant) {
321 $ret[$variant] = $this->translate($text, $variant);
324 wfProfileOut( $fname );
329 * convert link text to all supported variants
331 * @param string $text the text to be converted
332 * @return array of string
335 function convertLinkToAllVariants($text) {
336 if( !$this->mTablesLoaded
)
340 $tarray = explode($this->mMarkup
['begin'], $text);
341 $tfirst = array_shift($tarray);
343 foreach($this->mVariants
as $variant)
344 $ret[$variant] = $this->translate($tfirst,$variant);
346 foreach($tarray as $txt) {
347 $marked = explode($this->mMarkup
['end'], $txt, 2);
349 foreach($this->mVariants
as $variant){
350 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
351 if(array_key_exists(1, $marked))
352 $ret[$variant] .= $this->translate($marked[1],$variant);
361 * prepare manual conversion table
364 function prepareManualConv( $convRule ){
365 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
366 $title = $convRule->getTitle();
368 $this->mTitleFromFlag
= true;
369 $this->mTitleDisplay
= $title;
372 //apply manual conversion table to global table
373 $convTable = $convRule->getConvTable();
374 $action = $convRule->getRulesAction();
375 foreach( $convTable as $v => $t ) {
376 if( !in_array( $v, $this->mVariants
) )continue;
377 if( $action=="add" ) {
378 foreach( $t as $from => $to ) {
379 // to ensure that $from and $to not be left blank
380 // so $this->translate() could always return a string
382 // more efficient than array_merge(), about 2.5 times.
383 $this->mManualAddTables
[$v][$from] = $to;
386 elseif ( $action == "remove" ) {
387 foreach ( $t as $from=>$to ) {
389 $this->mManualRemoveTables
[$v][$from] = $to;
396 * apply manual conversion from $this->mManualAddTables and $this->mManualRemoveTables
399 function applyManualConv(){
400 //apply manual conversion table to global table
401 foreach($this->mVariants
as $v) {
402 if (count($this->mManualAddTables
[$v]) > 0) {
403 $this->mTables
[$v]->mergeArray($this->mManualAddTables
[$v]);
405 if (count($this->mManualRemoveTables
[$v]) > 0)
406 $this->mTables
[$v]->removeArray($this->mManualRemoveTables
[$v]);
411 * Convert text using a parser object for context
414 function parserConvert( $text, &$parser ) {
415 global $wgDisableLangConversion;
416 /* don't do anything if this is the conversion table */
417 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
418 strpos($parser->mTitle
->getText(), 'onversiontable') !== false )
423 if ( $wgDisableLangConversion )
426 $text = $this->convert( $text );
428 if ( $this->mTitleFromFlag
)
429 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
435 * @param string $title the title included namespace
436 * @return array of string
439 function convertNamespace( $title, $variant ) {
440 $splittitle = explode( ':', $title );
441 if (count($splittitle) < 2)
443 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) )
444 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
445 $ret = implode(':', $splittitle );
453 function convertTitle( $text, $variant ){
454 global $wgDisableTitleConversion, $wgUser;
456 // check for global param and __NOTC__ tag
457 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
$wgUser->getOption('noconvertlink') == 1 ) {
458 $this->mTitleDisplay
= $text;
462 // use the title from the T flag if any
463 if( $this->mTitleFromFlag
){
464 $this->mTitleFromFlag
= false;
465 return $this->mTitleDisplay
;
469 $isredir = $wgRequest->getText( 'redirect', 'yes' );
470 $action = $wgRequest->getText( 'action' );
471 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
472 if ( $isredir == 'no' ||
$action == 'edit' ||
$action == 'submit' ||
$linkconvert == 'no' ) {
475 $text = $this->convertNamespace( $text, $variant );
476 $this->mTitleDisplay
= $this->convert( $text );
477 return $this->mTitleDisplay
;
482 * convert text to different variants of a language. the automatic
483 * conversion is done in autoConvert(). here we parse the text
484 * marked with -{}-, which specifies special conversions of the
485 * text that can not be accomplished in autoConvert()
487 * syntax of the markup:
488 * -{code1:text1;code2:text2;...}- or
489 * -{flags|code1:text1;code2:text2;...}- or
490 * -{text}- in which case no conversion should take place for text
492 * @param string $text text to be converted
493 * @param bool $isTitle whether this conversion is for the article title
494 * @return string converted text
497 function convert( $text, $isTitle = false ) {
499 $mw =& MagicWord
::get( 'notitleconvert' );
500 if( $mw->matchAndRemove( $text ) )
501 $this->mDoTitleConvert
= false;
502 $mw =& MagicWord
::get( 'nocontentconvert' );
503 if( $mw->matchAndRemove( $text ) ) {
504 $this->mDoContentConvert
= false;
507 // no conversion if redirecting
508 $mw =& MagicWord
::get( 'redirect' );
509 if( $mw->matchStart( $text ) )
512 $plang = $this->getPreferredVariant();
514 // for title convertion
515 if ( $isTitle ) return $this->convertTitle( $text, $plang );
517 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
521 foreach ( $tarray as $txt ) {
522 $marked = explode( $this->mMarkup
['begin'], $txt, 2 );
523 if ( array_key_exists( 1, $marked ) ) {
524 $crule = new ConverterRule($marked[1], $this);
525 $crule->parse( $plang );
526 $marked[1] = $crule->getDisplay();
527 $this->prepareManualConv( $crule );
530 $marked[0] .= $this->mMarkup
['end'];
531 array_push( $marks, $marked );
533 $this->applyManualConv();
534 foreach ( $marks as $marked ) {
535 if( $this->mDoContentConvert
)
536 $text .= $this->autoConvert( $marked[0], $plang );
539 if( array_key_exists( 1, $marked ) )
542 // Remove the last delimiter (wasn't real)
543 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
549 * if a language supports multiple variants, it is
550 * possible that non-existing link in one variant
551 * actually exists in another variant. this function
552 * tries to find it. See e.g. LanguageZh.php
554 * @param string $link the name of the link
555 * @param mixed $nt the title object of the link
556 * @param boolean $ignoreOtherCond: to disable other conditions when
557 * we need to transclude a template or update a category's link
558 * @return null the input parameters may be modified upon return
561 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
562 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
563 $isredir = $wgRequest->getText( 'redirect', 'yes' );
564 $action = $wgRequest->getText( 'action' );
565 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
566 $disableLinkConversion = $wgDisableLangConversion ||
$wgDisableTitleConversion;
567 $linkBatch = new LinkBatch();
571 if ( $disableLinkConversion ||
( !$ignoreOtherCond && ( $isredir == 'no' ||
$action == 'edit'
572 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) )
576 $ns = $nt->getNamespace();
578 $variants = $this->autoConvertToAllVariants($link);
579 if($variants == false) //give up
584 foreach( $variants as $v ) {
586 $varnt = Title
::newFromText( $v, $ns );
587 if(!is_null($varnt)){
588 $linkBatch->addObj($varnt);
594 // fetch all variants in single query
595 $linkBatch->execute();
597 foreach( $titles as $varnt ) {
598 if( $varnt->getArticleID() > 0 ) {
600 $link = $varnt->getText();
607 * returns language specific hash options
611 function getExtraHashOptions() {
612 $variant = $this->getPreferredVariant();
613 return '!' . $variant ;
617 * get title text as defined in the body of the article text
621 function getParsedTitle() {
622 return $this->mTitleDisplay
;
626 * a write lock to the cache
630 function lockCache() {
633 for($i=0; $i<30; $i++
) {
634 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
646 function unlockCache() {
648 $wgMemc->delete($this->mCacheKey
. "lock");
653 * Load default conversion tables
654 * This method must be implemented in derived class
658 function loadDefaultTables() {
659 $name = get_class($this);
660 wfDie("Must implement loadDefaultTables() method in class $name");
664 * load conversion tables either from the cache or the disk
667 function loadTables( $fromcache = true ) {
669 if( $this->mTablesLoaded
)
671 wfProfileIn( __METHOD__
);
672 $this->mTablesLoaded
= true;
673 $this->mTables
= false;
675 wfProfileIn( __METHOD__
.'-cache' );
676 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
677 wfProfileOut( __METHOD__
.'-cache' );
679 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
680 wfProfileIn( __METHOD__
.'-recache' );
681 // not in cache, or we need a fresh reload.
682 // we will first load the default tables
683 // then update them using things in MediaWiki:Zhconversiontable/*
684 $this->loadDefaultTables();
685 foreach( $this->mVariants
as $var ) {
686 $cached = $this->parseCachedTable( $var );
687 // load group convert table, e.g. [[MediaWiki:Groupconversiontable-StarTrek]].
688 foreach( $this->mGroups
as $group ) {
689 $cachedgroup = $this->parseCachedTable( $var, '', true, "Groupconversiontable-$group" );
690 $cached = array_merge( $cached, $cachedgroup );
692 $this->mTables
[$var]->mergeArray( $cached );
695 $this->postLoadTables();
696 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
698 if($this->lockCache()) {
699 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
700 $this->unlockCache();
702 wfProfileOut( __METHOD__
.'-recache' );
704 wfProfileOut( __METHOD__
);
708 * Hook for post processig after conversion tables are loaded
711 function postLoadTables() {}
714 * Reload the conversion tables
718 function reloadTables() {
720 unset($this->mTables
);
721 $this->mTablesLoaded
= false;
722 $this->loadTables(false);
727 * parse the conversion table stored in the cache
729 * the tables should be in blocks of the following form:
736 * to make the tables more manageable, subpages are allowed
737 * and will be parsed recursively if $recursive=true
740 function parseCachedTable($code, $subpage='', $recursive=true, $table='Conversiontable') {
741 global $wgMessageCache;
742 static $parsed = array();
744 if(!is_object($wgMessageCache))
747 $key = "$table/".$code;
749 $key .= '/' . $subpage;
751 if(array_key_exists($key, $parsed))
754 if ( strpos( $code, '/' ) === false ) {
755 $txt = $wgMessageCache->get( $table, true, $code );
757 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "$table/$code" );
758 if ( $title && $title->exists() ) {
759 $article = new Article( $title );
760 $txt = $article->getContents();
765 // get all subpage links of the form
766 // [[MediaWiki:conversiontable/zh-xx/...|...]]
767 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ":$table";
768 $subs = explode('[[', $txt);
770 foreach( $subs as $sub ) {
771 $link = explode(']]', $sub, 2);
772 if(count($link) != 2)
774 $b = explode('|', $link[0]);
775 $b = explode('/', trim($b[0]), 3);
781 if($b[0] == $linkhead && $b[1] == $code) {
782 $sublinks[] = $sublink;
786 // parse the mappings in this page
787 $blocks = explode($this->mMarkup
['begin'], $txt);
788 array_shift($blocks);
790 foreach($blocks as $block) {
791 $mappings = explode($this->mMarkup
['end'], $block, 2);
792 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
793 $table = explode( ';', $stripped );
794 foreach( $table as $t ) {
795 $m = explode( '=>', $t );
796 if( count( $m ) != 2)
798 // trim any trailling comments starting with '//'
799 $tt = explode('//', $m[1], 2);
800 $ret[trim($m[0])] = trim($tt[0]);
803 $parsed[$key] = true;
806 // recursively parse the subpages
808 foreach($sublinks as $link) {
809 $s = $this->parseCachedTable($code, $link, $recursive);
810 $ret = array_merge($ret, $s);
814 if ($this->mUcfirst
) {
815 foreach ($ret as $k => $v) {
816 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
823 * Enclose a string with the "no conversion" tag. This is used by
824 * various functions in the Parser
826 * @param string $text text to be tagged for no conversion
827 * @return string the tagged text
830 function markNoConversion($text, $noParse=false) {
831 # don't mark if already marked
832 if(strpos($text, $this->mMarkup
['begin']) ||
833 strpos($text, $this->mMarkup
['end']))
836 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
841 * convert the sorting key for category links. this should make different
842 * keys that are variants of each other map to the same key
844 function convertCategoryKey( $key ) {
848 * hook to refresh the cache of conversion tables when
849 * MediaWiki:conversiontable* is updated
852 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
853 $titleobj = $article->getTitle();
854 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
855 $title = $titleobj->getDBkey();
856 $t = explode('/', $title, 3);
858 if( $c > 1 && $t[0] == 'Conversiontable' ) {
859 if(in_array($t[1], $this->mVariants
)) {
860 $this->reloadTables();
868 * Armour rendered math against conversion
869 * Wrap math into rawoutput -{R| math }- syntax
872 function armourMath($text){
873 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
878 * Callback function for magicword 'groupconvert'
880 * @param string $group: the group name called for
881 * @return blank string
883 function groupConvert( $group ) {
884 $this->mGroups
[] = $group;
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 = '',$mRuleTitle=false;
899 var $mRules = '';// string : the text of the rules
900 var $mRulesAction = 'none';
901 var $mFlags = array();
902 var $mConvTable = array();
903 var $mBidtable = array();// array of the translation in each variant
904 var $mUnidtable = array();// array of the translation in each variant
909 * @param string $text the text between -{ and }-
910 * @param object $converter a LanguageConverter object
913 function __construct($text,$converter){
914 $this->mText
= $text;
915 $this->mConverter
=$converter;
916 foreach($converter->mVariants
as $v){
917 $this->mConvTable
[$v]=array();
922 * check if variants array in convert array
924 * @param string $variant Variant language code
925 * @return string Translated text
928 function getTextInBidtable($variants){
929 if(is_string($variants)){ $variants=array($variants); }
930 if(!is_array($variants)) return false;
931 foreach ($variants as $variant){
932 if(array_key_exists($variant, $this->mBidtable
)){
933 return $this->mBidtable
[$variant];
940 * Parse flags with syntax -{FLAG| ... }-
943 function parseFlags(){
944 $text = $this->mText
;
945 if(strlen($text) < 2 ) {
946 $this->mFlags
= array( 'R' );
947 $this->mRules
= $text;
952 $markup = $this->mConverter
->mMarkup
;
953 $validFlags = $this->mConverter
->mFlags
;
954 $variants = $this->mConverter
->mVariants
;
956 $tt = explode($markup['flagsep'], $text, 2);
957 if(count($tt) == 2) {
958 $f = explode($markup['varsep'], $tt[0]);
961 if(array_key_exists($ff, $validFlags) &&
962 !in_array($validFlags[$ff], $flags))
963 $flags[] = $validFlags[$ff];
971 if( in_array('R',$flags) ){
972 $flags = array('R');// remove other flags
973 } elseif ( in_array('N',$flags) ){
974 $flags = array('N');// remove other flags
975 } elseif ( in_array('-',$flags) ){
976 $flags = array('-');// remove other flags
977 } elseif (count($flags)==1 && $flags[0]=='T'){
979 } elseif ( in_array('H',$flags) ){
980 // replace A flag, and remove other flags except T
981 $temp=array('+','H');
982 if(in_array('T',$flags)) $temp[] = 'T';
983 if(in_array('D',$flags)) $temp[] = 'D';
986 if ( in_array('A',$flags) ) {
990 if ( in_array('D',$flags) )
991 $flags=array_diff($flags,array('S'));
992 $flags_temp = array();
993 foreach ($variants as $variant) {
994 // try to find flags like "zh-hans", "zh-hant"
995 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
996 if ( in_array($variant, $flags) )
997 $flags_temp[] = $variant;
999 if ( count($flags_temp) !== 0 )
1000 $flags = $flags_temp;
1002 if ( count($flags) == 0 )
1003 $flags = array('S');
1004 $this->mRules
=$rules;
1005 $this->mFlags
=$flags;
1009 * generate conversion table
1012 function parseRules() {
1013 $rules = $this->mRules
;
1014 $flags = $this->mFlags
;
1015 $bidtable = array();
1016 $unidtable = array();
1017 $markup = $this->mConverter
->mMarkup
;
1018 $variants = $this->mConverter
->mVariants
;
1020 // varsep_pattern for preg_split:
1021 // text should be splited by ";" only if a valid variant
1022 // name exist after the markup, for example:
1023 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
1024 // we should split it as:
1026 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1027 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1030 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1031 foreach( $variants as $variant ) {
1032 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
1033 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1034 . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1036 $varsep_pattern .= '\s*$)/';
1038 $choice = preg_split($varsep_pattern, $rules);
1040 foreach( $choice as $c ) {
1041 $v = explode($markup['codesep'], $c, 2);
1042 if( count($v) != 2 )
1043 continue;// syntax error, skip
1046 $u = explode($markup['unidsep'], $v);
1047 // if $to is empty, strtr() could return a wrong result
1048 if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
1049 $bidtable[$v] = $to;
1050 } else if(count($u) == 2){
1051 $from = trim($u[0]);
1053 if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
1054 && $to && in_array( $v, $variants ) )
1055 $unidtable[$v] = array( $from=>$to );
1056 elseif ( $to && in_array( $v, $variants ) )
1057 $unidtable[$v][$from] = $to;
1059 // syntax error, pass
1060 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ){
1061 $bidtable = array();
1062 $unidtable = array();
1066 $this->mBidtable
= $bidtable;
1067 $this->mUnidtable
= $unidtable;
1073 function getRulesDesc(){
1074 $codesep = $this->mConverter
->mDescCodeSep
;
1075 $varsep = $this->mConverter
->mDescVarSep
;
1077 foreach($this->mBidtable
as $k => $v)
1078 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
1079 foreach($this->mUnidtable
as $k => $a)
1080 foreach($a as $from=>$to)
1081 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
1086 * Parse rules conversion
1089 function getRuleConvertedStr($variant,$doConvert){
1090 $bidtable = $this->mBidtable
;
1091 $unidtable = $this->mUnidtable
;
1093 if( count($bidtable) +
count($unidtable) == 0 ){
1094 return $this->mRules
;
1095 } elseif ($doConvert){// the text converted
1096 // display current variant in bidirectional array
1097 $disp = $this->getTextInBidtable($variant);
1098 // or display current variant in fallbacks
1100 $disp = $this->getTextInBidtable(
1101 $this->mConverter
->getVariantFallbacks($variant));
1102 // or display current variant in unidirectional array
1103 if(!$disp && array_key_exists($variant,$unidtable)){
1104 $disp = array_values($unidtable[$variant]);
1107 // or display frist text under disable manual convert
1108 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
1109 if(count($bidtable)>0){
1110 $disp = array_values($bidtable);
1113 $disp = array_values($unidtable);
1114 $disp = array_values($disp[0]);
1119 } else {// no convert
1120 return $this->mRules
;
1125 * generate conversion table for all text
1128 function generateConvTable(){
1129 $flags = $this->mFlags
;
1130 $bidtable = $this->mBidtable
;
1131 $unidtable = $this->mUnidtable
;
1132 $manLevel = $this->mConverter
->mManualLevel
;
1135 foreach($this->mConverter
->mVariants
as $v) {
1136 /* for bidirectional array
1137 fill in the missing variants, if any,
1139 if(!array_key_exists($v, $bidtable)) {
1140 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
1141 $vf = $this->getTextInBidtable($variantFallbacks);
1142 if($vf) $bidtable[$v] = $vf;
1145 if(array_key_exists($v,$bidtable)){
1146 foreach($vmarked as $vo){
1147 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1148 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1149 // to introduce a custom mapping between
1150 // words WordZh and WordTw in the whole text
1151 if($manLevel[$v]=='bidirectional'){
1152 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1154 if($manLevel[$vo]=='bidirectional'){
1155 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1160 /*for unidirectional array
1161 fill to convert tables */
1162 $allow_unid = $manLevel[$v]=='bidirectional'
1163 ||
$manLevel[$v]=='unidirectional';
1164 if($allow_unid && array_key_exists($v,$unidtable)){
1165 $ct=$this->mConvTable
[$v];
1166 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1172 * Parse rules and flags
1175 function parse($variant){
1177 $variant = $this->mConverter
->getPreferredVariant();
1179 $variants = $this->mConverter
->mVariants
;
1180 $this->parseFlags();
1181 $flags = $this->mFlags
;
1183 // convert to specified variant
1184 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1185 if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
1186 if ( in_array( $variant, $flags ) ) // check if current variant in flags
1187 // then convert <text to convert> to current language
1188 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variant );
1189 else { // if current variant no in flags,
1190 // then we check its fallback variants.
1191 $variantFallbacks = $this->mConverter
->getVariantFallbacks($variant);
1192 foreach ( $variantFallbacks as $variantFallback ) {
1193 // if current variant's fallback exist in flags
1194 if ( in_array( $variantFallback, $flags ) ) {
1195 // then convert <text to convert> to fallback language
1196 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variantFallback );
1201 $this->mFlags
= $flags = array('R');
1204 if( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1205 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1206 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1208 $this->parseRules();
1210 $rules = $this->mRules
;
1212 if( count( $this->mBidtable
) == 0 && count( $this->mUnidtable
) == 0 ){
1213 if(in_array('+',$flags) ||
in_array('-',$flags))
1214 // fill all variants if text in -{A/H/-|text} without rules
1215 foreach($this->mConverter
->mVariants
as $v)
1216 $this->mBidtable
[$v] = $rules;
1217 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1218 $this->mFlags
= $flags = array('R');
1221 if( in_array('R',$flags) ) {
1222 // if we don't do content convert, still strip the -{}- tags
1223 $this->mRuleDisplay
= $rules;
1224 } elseif ( in_array('N',$flags) ){
1225 // proces N flag: output current variant name
1226 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1227 } elseif ( in_array('D',$flags) ){
1228 // proces D flag: output rules description
1229 $this->mRuleDisplay
= $this->getRulesDesc();
1230 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1231 // proces H,- flag or T only: output nothing
1232 $this->mRuleDisplay
= '';
1233 } elseif ( in_array('S',$flags) ){
1234 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1235 $this->mConverter
->mDoContentConvert
);
1237 $this->mRuleDisplay
= $this->mManualCodeError
;
1240 if ( in_array('T',$flags) ) {
1241 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1242 $this->mConverter
->mDoTitleConvert
);
1245 if (in_array('-', $flags))
1246 $this->mRulesAction
='remove';
1247 if (in_array('+', $flags))
1248 $this->mRulesAction
='add';
1250 $this->generateConvTable();
1256 function hasRules(){
1261 * get display text on markup -{...}-
1264 function getDisplay(){
1265 return $this->mRuleDisplay
;
1268 * get converted title
1271 function getTitle(){
1272 return $this->mRuleTitle
;
1276 * return how deal with conversion rules
1279 function getRulesAction(){
1280 return $this->mRulesAction
;
1284 * get conversion table ( bidirectional and unidirectional conversion table )
1287 function getConvTable(){
1288 return $this->mConvTable
;
1292 * get conversion rules string
1295 function getRules(){
1296 return $this->mRules
;
1300 * get conversion flags
1303 function getFlags(){
1304 return $this->mFlags
;