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"]));
189 $result = explode(',', $acceptLanguage);
191 $languages = array();
193 foreach( $result as $elem ) {
194 // if $elem likes 'zh-cn;q=0.9'
195 if(($posi = strpos( $elem, ';' )) !== false ) {
196 // get the real language code likes 'zh-cn'
197 $languages[] = substr( $elem, 0, $posi );
200 $languages[] = $elem;
204 foreach( $languages as $language ) {
206 $language = trim( $language );
207 if( in_array( $language, $this->mVariants
) ) {
215 return $this->mMainLanguageCode
;
220 * caption convert, base on preg_replace_callback
222 * to convert text in "title" or "alt", like '<img alt="text" ... '
223 * or '<span title="text" ... '
225 * @return string like ' alt="yyyy"' or ' title="yyyy"'
228 function captionConvert( $matches ) {
229 $toVariant = $this->getPreferredVariant();
230 $title = $matches[1];
232 // we convert captions except URL
233 if( !strpos( $text, '://' ) )
234 $text = $this->translate($text, $toVariant);
235 return " $title=\"$text\"";
239 * dictionary-based conversion
241 * @param string $text the text to be converted
242 * @param string $toVariant the target language code
243 * @return string the converted text
246 function autoConvert($text, $toVariant=false) {
247 $fname="LanguageConverter::autoConvert";
249 wfProfileIn( $fname );
251 if(!$this->mTablesLoaded
)
255 $toVariant = $this->getPreferredVariant();
256 if(!in_array($toVariant, $this->mVariants
))
259 /* we convert everything except:
260 1. html markups (anything between < and >)
262 3. place holders created by the parser
265 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
266 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
270 // this one is needed when the text is inside an html markup
271 $htmlfix = '|<[^>]+$|^[^<>]*>';
273 // disable convert to variants between <code></code> tags
274 $codefix = '<code>.+?<\/code>|';
275 // disable convertsion of <script type="text/javascript"> ... </script>
276 $scriptfix = '<script.*?>.*?<\/script>|';
277 // disable conversion of <pre xxxx> ... </pre>
278 $prefix = '<pre.*?>.*?<\/pre>|';
280 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
282 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
284 $m = array_shift($matches);
286 $ret = $this->translate($m[0], $toVariant);
287 $mstart = $m[1]+
strlen($m[0]);
289 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
290 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
291 foreach($matches as $m) {
292 $mark = substr($text, $mstart, $m[1]-$mstart);
293 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
295 $ret .= $this->translate($m[0], $toVariant);
296 $mstart = $m[1] +
strlen($m[0]);
298 wfProfileOut( $fname );
303 * Translate a string to a variant
304 * Doesn't process markup or do any of that other stuff, for that use convert()
306 * @param string $text Text to convert
307 * @param string $variant Variant language code
308 * @return string Translated text
311 function translate( $text, $variant ) {
312 wfProfileIn( __METHOD__
);
313 if( !$this->mTablesLoaded
)
315 $text = $this->mTables
[$variant]->replace( $text );
316 wfProfileOut( __METHOD__
);
321 * convert text to all supported variants
323 * @param string $text the text to be converted
324 * @return array of string
327 function autoConvertToAllVariants($text) {
328 $fname="LanguageConverter::autoConvertToAllVariants";
329 wfProfileIn( $fname );
330 if( !$this->mTablesLoaded
)
334 foreach($this->mVariants
as $variant) {
335 $ret[$variant] = $this->translate($text, $variant);
338 wfProfileOut( $fname );
343 * convert link text to all supported variants
345 * @param string $text the text to be converted
346 * @return array of string
349 function convertLinkToAllVariants($text) {
350 if( !$this->mTablesLoaded
)
354 $tarray = explode($this->mMarkup
['begin'], $text);
355 $tfirst = array_shift($tarray);
357 foreach($this->mVariants
as $variant)
358 $ret[$variant] = $this->translate($tfirst,$variant);
360 foreach($tarray as $txt) {
361 $marked = explode($this->mMarkup
['end'], $txt, 2);
363 foreach($this->mVariants
as $variant){
364 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
365 if(array_key_exists(1, $marked))
366 $ret[$variant] .= $this->translate($marked[1],$variant);
375 * prepare manual conversion table
378 function prepareManualConv( $convRule ){
379 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
380 $title = $convRule->getTitle();
382 $this->mTitleFromFlag
= true;
383 $this->mTitleDisplay
= $title;
386 //apply manual conversion table to global table
387 $convTable = $convRule->getConvTable();
388 $action = $convRule->getRulesAction();
389 foreach( $convTable as $v => $t ) {
390 if( !in_array( $v, $this->mVariants
) )continue;
391 if( $action=="add" ) {
392 foreach( $t as $from => $to ) {
393 // to ensure that $from and $to not be left blank
394 // so $this->translate() could always return a string
396 // more efficient than array_merge(), about 2.5 times.
397 $this->mManualAddTables
[$v][$from] = $to;
400 elseif ( $action == "remove" ) {
401 foreach ( $t as $from=>$to ) {
403 $this->mManualRemoveTables
[$v][$from] = $to;
410 * apply manual conversion from $this->mManualAddTables and $this->mManualRemoveTables
413 function applyManualConv(){
414 //apply manual conversion table to global table
415 foreach($this->mVariants
as $v) {
416 if (count($this->mManualAddTables
[$v]) > 0) {
417 $this->mTables
[$v]->mergeArray($this->mManualAddTables
[$v]);
419 if (count($this->mManualRemoveTables
[$v]) > 0)
420 $this->mTables
[$v]->removeArray($this->mManualRemoveTables
[$v]);
425 * Convert text using a parser object for context
428 function parserConvert( $text, &$parser ) {
429 global $wgUser, $wgEnableVariants;
431 /* disable entire conversion engine if the user had been disabled it */
432 $variantConv = $wgUser->getOption( 'variantconversion' );
433 if ( ( $wgEnableVariants == true ) && ( $variantConv == 0 ) ) {
434 $wgEnableVariants = false;
437 /* don't do anything if this is the conversion table */
438 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
439 strpos($parser->mTitle
->getText(), 'onversiontable') !== false )
444 if ( !$wgEnableVariants )
447 $text = $this->convert( $text );
449 if ( $this->mTitleFromFlag
)
450 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
456 * @param string $title the title included namespace
457 * @return array of string
460 function convertNamespace( $title, $variant ) {
461 $splittitle = explode( ':', $title );
462 if (count($splittitle) < 2)
464 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) )
465 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
466 $ret = implode(':', $splittitle );
474 function convertTitle( $text, $variant ){
475 global $wgDisableTitleConversion, $wgUser;
477 // check for global param and __NOTC__ tag
478 if( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
$wgUser->getOption('noconvertlink') == 1 ) {
479 $this->mTitleDisplay
= $text;
483 // use the title from the T flag if any
484 if( $this->mTitleFromFlag
){
485 $this->mTitleFromFlag
= false;
486 return $this->mTitleDisplay
;
490 $isredir = $wgRequest->getText( 'redirect', 'yes' );
491 $action = $wgRequest->getText( 'action' );
492 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
493 if ( $isredir == 'no' ||
$action == 'edit' ||
$action == 'submit' ||
$linkconvert == 'no' ) {
496 $text = $this->convertNamespace( $text, $variant );
497 $this->mTitleDisplay
= $this->convert( $text );
498 return $this->mTitleDisplay
;
503 * convert text to different variants of a language. the automatic
504 * conversion is done in autoConvert(). here we parse the text
505 * marked with -{}-, which specifies special conversions of the
506 * text that can not be accomplished in autoConvert()
508 * syntax of the markup:
509 * -{code1:text1;code2:text2;...}- or
510 * -{flags|code1:text1;code2:text2;...}- or
511 * -{text}- in which case no conversion should take place for text
513 * @param string $text text to be converted
514 * @param bool $isTitle whether this conversion is for the article title
515 * @return string converted text
518 function convert( $text, $isTitle = false ) {
520 $mw =& MagicWord
::get( 'notitleconvert' );
521 if( $mw->matchAndRemove( $text ) )
522 $this->mDoTitleConvert
= false;
523 $mw =& MagicWord
::get( 'nocontentconvert' );
524 if( $mw->matchAndRemove( $text ) ) {
525 $this->mDoContentConvert
= false;
528 // no conversion if redirecting
529 $mw =& MagicWord
::get( 'redirect' );
530 if( $mw->matchStart( $text ) )
533 $plang = $this->getPreferredVariant();
535 // for title convertion
536 if ( $isTitle ) return $this->convertTitle( $text, $plang );
538 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
542 foreach ( $tarray as $txt ) {
543 $marked = explode( $this->mMarkup
['begin'], $txt, 2 );
544 if ( array_key_exists( 1, $marked ) ) {
545 $crule = new ConverterRule($marked[1], $this);
546 $crule->parse( $plang );
547 $marked[1] = $crule->getDisplay();
548 $this->prepareManualConv( $crule );
551 $marked[0] .= $this->mMarkup
['end'];
552 array_push( $marks, $marked );
554 $this->applyManualConv();
555 foreach ( $marks as $marked ) {
556 if( $this->mDoContentConvert
)
557 $text .= $this->autoConvert( $marked[0], $plang );
560 if( array_key_exists( 1, $marked ) )
563 // Remove the last delimiter (wasn't real)
564 $text = substr( $text, 0, -strlen( $this->mMarkup
['end'] ) );
570 * if a language supports multiple variants, it is
571 * possible that non-existing link in one variant
572 * actually exists in another variant. this function
573 * tries to find it. See e.g. LanguageZh.php
575 * @param string $link the name of the link
576 * @param mixed $nt the title object of the link
577 * @param boolean $ignoreOtherCond: to disable other conditions when
578 * we need to transclude a template or update a category's link
579 * @return null the input parameters may be modified upon return
582 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
583 global $wgEnableVariants, $wgDisableTitleConversion, $wgRequest, $wgUser;
584 $isredir = $wgRequest->getText( 'redirect', 'yes' );
585 $action = $wgRequest->getText( 'action' );
586 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
587 $disableLinkConversion = !$wgEnableVariants ||
$wgDisableTitleConversion;
588 $linkBatch = new LinkBatch();
592 if ( $disableLinkConversion ||
( !$ignoreOtherCond && ( $isredir == 'no' ||
$action == 'edit'
593 ||
$action == 'submit' ||
$linkconvert == 'no' ||
$wgUser->getOption('noconvertlink') == 1 ) ) )
597 $ns = $nt->getNamespace();
599 $variants = $this->autoConvertToAllVariants($link);
600 if($variants == false) //give up
605 foreach( $variants as $v ) {
607 $varnt = Title
::newFromText( $v, $ns );
608 if(!is_null($varnt)){
609 $linkBatch->addObj($varnt);
615 // fetch all variants in single query
616 $linkBatch->execute();
618 foreach( $titles as $varnt ) {
619 if( $varnt->getArticleID() > 0 ) {
621 $link = $varnt->getText();
628 * returns language specific hash options
632 function getExtraHashOptions() {
633 $variant = $this->getPreferredVariant();
634 return '!' . $variant ;
638 * get title text as defined in the body of the article text
642 function getParsedTitle() {
643 return $this->mTitleDisplay
;
647 * a write lock to the cache
651 function lockCache() {
654 for($i=0; $i<30; $i++
) {
655 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
667 function unlockCache() {
669 $wgMemc->delete($this->mCacheKey
. "lock");
674 * Load default conversion tables
675 * This method must be implemented in derived class
679 function loadDefaultTables() {
680 $name = get_class($this);
681 wfDie("Must implement loadDefaultTables() method in class $name");
685 * load conversion tables either from the cache or the disk
688 function loadTables( $fromcache = true ) {
690 if( $this->mTablesLoaded
)
692 wfProfileIn( __METHOD__
);
693 $this->mTablesLoaded
= true;
694 $this->mTables
= false;
696 wfProfileIn( __METHOD__
.'-cache' );
697 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
698 wfProfileOut( __METHOD__
.'-cache' );
700 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
701 wfProfileIn( __METHOD__
.'-recache' );
702 // not in cache, or we need a fresh reload.
703 // we will first load the default tables
704 // then update them using things in MediaWiki:Zhconversiontable/*
705 $this->loadDefaultTables();
706 foreach( $this->mVariants
as $var ) {
707 $cached = $this->parseCachedTable( $var );
708 // load group convert table, e.g. [[MediaWiki:Groupconversiontable-StarTrek]].
709 foreach( $this->mGroups
as $group ) {
710 $cachedgroup = $this->parseCachedTable( $var, '', true, "Groupconversiontable-$group" );
711 $cached = array_merge( $cached, $cachedgroup );
713 $this->mTables
[$var]->mergeArray( $cached );
716 $this->postLoadTables();
717 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
719 if($this->lockCache()) {
720 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
721 $this->unlockCache();
723 wfProfileOut( __METHOD__
.'-recache' );
725 wfProfileOut( __METHOD__
);
729 * Hook for post processig after conversion tables are loaded
732 function postLoadTables() {}
735 * Reload the conversion tables
739 function reloadTables() {
741 unset($this->mTables
);
742 $this->mTablesLoaded
= false;
743 $this->loadTables(false);
748 * parse the conversion table stored in the cache
750 * the tables should be in blocks of the following form:
757 * to make the tables more manageable, subpages are allowed
758 * and will be parsed recursively if $recursive=true
761 function parseCachedTable($code, $subpage='', $recursive=true, $table='Conversiontable') {
762 global $wgMessageCache;
763 static $parsed = array();
765 if(!is_object($wgMessageCache))
768 $key = "$table/".$code;
770 $key .= '/' . $subpage;
772 if(array_key_exists($key, $parsed))
775 if ( strpos( $code, '/' ) === false ) {
776 $txt = $wgMessageCache->get( $table, true, $code );
778 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, "$table/$code" );
779 if ( $title && $title->exists() ) {
780 $article = new Article( $title );
781 $txt = $article->getContents();
786 // get all subpage links of the form
787 // [[MediaWiki:conversiontable/zh-xx/...|...]]
788 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ":$table";
789 $subs = explode('[[', $txt);
791 foreach( $subs as $sub ) {
792 $link = explode(']]', $sub, 2);
793 if(count($link) != 2)
795 $b = explode('|', $link[0]);
796 $b = explode('/', trim($b[0]), 3);
802 if($b[0] == $linkhead && $b[1] == $code) {
803 $sublinks[] = $sublink;
807 // parse the mappings in this page
808 $blocks = explode($this->mMarkup
['begin'], $txt);
809 array_shift($blocks);
811 foreach($blocks as $block) {
812 $mappings = explode($this->mMarkup
['end'], $block, 2);
813 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
814 $table = explode( ';', $stripped );
815 foreach( $table as $t ) {
816 $m = explode( '=>', $t );
817 if( count( $m ) != 2)
819 // trim any trailling comments starting with '//'
820 $tt = explode('//', $m[1], 2);
821 $ret[trim($m[0])] = trim($tt[0]);
824 $parsed[$key] = true;
827 // recursively parse the subpages
829 foreach($sublinks as $link) {
830 $s = $this->parseCachedTable($code, $link, $recursive);
831 $ret = array_merge($ret, $s);
835 if ($this->mUcfirst
) {
836 foreach ($ret as $k => $v) {
837 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
844 * Enclose a string with the "no conversion" tag. This is used by
845 * various functions in the Parser
847 * @param string $text text to be tagged for no conversion
848 * @return string the tagged text
851 function markNoConversion($text, $noParse=false) {
852 # don't mark if already marked
853 if(strpos($text, $this->mMarkup
['begin']) ||
854 strpos($text, $this->mMarkup
['end']))
857 $ret = $this->mMarkup
['begin'] .'R|'. $text . $this->mMarkup
['end'];
862 * convert the sorting key for category links. this should make different
863 * keys that are variants of each other map to the same key
865 function convertCategoryKey( $key ) {
869 * hook to refresh the cache of conversion tables when
870 * MediaWiki:conversiontable* is updated
873 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
874 $titleobj = $article->getTitle();
875 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
876 $title = $titleobj->getDBkey();
877 $t = explode('/', $title, 3);
879 if( $c > 1 && $t[0] == 'Conversiontable' ) {
880 if(in_array($t[1], $this->mVariants
)) {
881 $this->reloadTables();
889 * Armour rendered math against conversion
890 * Wrap math into rawoutput -{R| math }- syntax
893 function armourMath($text){
894 // we need to convert '-{' and '}-' to '-{' and '}-'
895 // to avoid a unwanted '}-' appeared after the math-image.
896 $text = strtr( $text, array('-{' => '-{', '}-' => '}-') );
897 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
902 * Callback function for magicword 'groupconvert'
904 * @param string $group: the group name called for
905 * @return blank string
907 function groupConvert( $group ) {
908 $this->mGroups
[] = $group;
914 * parser for rules of language conversion , parse rules in -{ }- tag
916 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
918 class ConverterRule
{
919 var $mText; // original text in -{text}-
920 var $mConverter; // LanguageConverter object
921 var $mManualCodeError='<strong class="error">code error!</strong>';
922 var $mRuleDisplay = '',$mRuleTitle=false;
923 var $mRules = '';// string : the text of the rules
924 var $mRulesAction = 'none';
925 var $mFlags = array();
926 var $mConvTable = array();
927 var $mBidtable = array();// array of the translation in each variant
928 var $mUnidtable = array();// array of the translation in each variant
933 * @param string $text the text between -{ and }-
934 * @param object $converter a LanguageConverter object
937 function __construct($text,$converter){
938 $this->mText
= $text;
939 $this->mConverter
=$converter;
940 foreach($converter->mVariants
as $v){
941 $this->mConvTable
[$v]=array();
946 * check if variants array in convert array
948 * @param string $variant Variant language code
949 * @return string Translated text
952 function getTextInBidtable($variants){
953 if(is_string($variants)){ $variants=array($variants); }
954 if(!is_array($variants)) return false;
955 foreach ($variants as $variant){
956 if(array_key_exists($variant, $this->mBidtable
)){
957 return $this->mBidtable
[$variant];
964 * Parse flags with syntax -{FLAG| ... }-
967 function parseFlags(){
968 $text = $this->mText
;
969 if(strlen($text) < 2 ) {
970 $this->mFlags
= array( 'R' );
971 $this->mRules
= $text;
976 $markup = $this->mConverter
->mMarkup
;
977 $validFlags = $this->mConverter
->mFlags
;
978 $variants = $this->mConverter
->mVariants
;
980 $tt = explode($markup['flagsep'], $text, 2);
981 if(count($tt) == 2) {
982 $f = explode($markup['varsep'], $tt[0]);
985 if(array_key_exists($ff, $validFlags) &&
986 !in_array($validFlags[$ff], $flags))
987 $flags[] = $validFlags[$ff];
995 if( in_array('R',$flags) ){
996 $flags = array('R');// remove other flags
997 } elseif ( in_array('N',$flags) ){
998 $flags = array('N');// remove other flags
999 } elseif ( in_array('-',$flags) ){
1000 $flags = array('-');// remove other flags
1001 } elseif (count($flags)==1 && $flags[0]=='T'){
1003 } elseif ( in_array('H',$flags) ){
1004 // replace A flag, and remove other flags except T
1005 $temp=array('+','H');
1006 if(in_array('T',$flags)) $temp[] = 'T';
1007 if(in_array('D',$flags)) $temp[] = 'D';
1010 if ( in_array('A',$flags) ) {
1014 if ( in_array('D',$flags) )
1015 $flags=array_diff($flags,array('S'));
1016 $flags_temp = array();
1017 foreach ($variants as $variant) {
1018 // try to find flags like "zh-hans", "zh-hant"
1019 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1020 if ( in_array($variant, $flags) )
1021 $flags_temp[] = $variant;
1023 if ( count($flags_temp) !== 0 )
1024 $flags = $flags_temp;
1026 if ( count($flags) == 0 )
1027 $flags = array('S');
1028 $this->mRules
=$rules;
1029 $this->mFlags
=$flags;
1033 * generate conversion table
1036 function parseRules() {
1037 $rules = $this->mRules
;
1038 $flags = $this->mFlags
;
1039 $bidtable = array();
1040 $unidtable = array();
1041 $markup = $this->mConverter
->mMarkup
;
1042 $variants = $this->mConverter
->mVariants
;
1044 // varsep_pattern for preg_split:
1045 // text should be splited by ";" only if a valid variant
1046 // name exist after the markup, for example:
1047 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
1048 // we should split it as:
1050 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1051 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1054 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1055 foreach( $variants as $variant ) {
1056 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
1057 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1058 . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1060 $varsep_pattern .= '\s*$)/';
1062 $choice = preg_split($varsep_pattern, $rules);
1064 foreach( $choice as $c ) {
1065 $v = explode($markup['codesep'], $c, 2);
1066 if( count($v) != 2 )
1067 continue;// syntax error, skip
1070 $u = explode($markup['unidsep'], $v);
1071 // if $to is empty, strtr() could return a wrong result
1072 if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
1073 $bidtable[$v] = $to;
1074 } else if(count($u) == 2){
1075 $from = trim($u[0]);
1077 if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
1078 && $to && in_array( $v, $variants ) )
1079 $unidtable[$v] = array( $from=>$to );
1080 elseif ( $to && in_array( $v, $variants ) )
1081 $unidtable[$v][$from] = $to;
1083 // syntax error, pass
1084 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ){
1085 $bidtable = array();
1086 $unidtable = array();
1090 $this->mBidtable
= $bidtable;
1091 $this->mUnidtable
= $unidtable;
1097 function getRulesDesc(){
1098 $codesep = $this->mConverter
->mDescCodeSep
;
1099 $varsep = $this->mConverter
->mDescVarSep
;
1101 foreach($this->mBidtable
as $k => $v)
1102 $text .= $this->mConverter
->mVariantNames
[$k]."$codesep$v$varsep";
1103 foreach($this->mUnidtable
as $k => $a)
1104 foreach($a as $from=>$to)
1105 $text.=$from.'⇒'.$this->mConverter
->mVariantNames
[$k]."$codesep$to$varsep";
1110 * Parse rules conversion
1113 function getRuleConvertedStr($variant,$doConvert){
1114 $bidtable = $this->mBidtable
;
1115 $unidtable = $this->mUnidtable
;
1117 if( count($bidtable) +
count($unidtable) == 0 ){
1118 return $this->mRules
;
1119 } elseif ($doConvert){// the text converted
1120 // display current variant in bidirectional array
1121 $disp = $this->getTextInBidtable($variant);
1122 // or display current variant in fallbacks
1124 $disp = $this->getTextInBidtable(
1125 $this->mConverter
->getVariantFallbacks($variant));
1126 // or display current variant in unidirectional array
1127 if(!$disp && array_key_exists($variant,$unidtable)){
1128 $disp = array_values($unidtable[$variant]);
1131 // or display frist text under disable manual convert
1132 if(!$disp && $this->mConverter
->mManualLevel
[$variant]=='disable') {
1133 if(count($bidtable)>0){
1134 $disp = array_values($bidtable);
1137 $disp = array_values($unidtable);
1138 $disp = array_values($disp[0]);
1143 } else {// no convert
1144 return $this->mRules
;
1149 * generate conversion table for all text
1152 function generateConvTable(){
1153 $flags = $this->mFlags
;
1154 $bidtable = $this->mBidtable
;
1155 $unidtable = $this->mUnidtable
;
1156 $manLevel = $this->mConverter
->mManualLevel
;
1159 foreach($this->mConverter
->mVariants
as $v) {
1160 /* for bidirectional array
1161 fill in the missing variants, if any,
1163 if(!array_key_exists($v, $bidtable)) {
1164 $variantFallbacks = $this->mConverter
->getVariantFallbacks($v);
1165 $vf = $this->getTextInBidtable($variantFallbacks);
1166 if($vf) $bidtable[$v] = $vf;
1169 if(array_key_exists($v,$bidtable)){
1170 foreach($vmarked as $vo){
1171 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1172 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1173 // to introduce a custom mapping between
1174 // words WordZh and WordTw in the whole text
1175 if($manLevel[$v]=='bidirectional'){
1176 $this->mConvTable
[$v][$bidtable[$vo]]=$bidtable[$v];
1178 if($manLevel[$vo]=='bidirectional'){
1179 $this->mConvTable
[$vo][$bidtable[$v]]=$bidtable[$vo];
1184 /*for unidirectional array
1185 fill to convert tables */
1186 $allow_unid = $manLevel[$v]=='bidirectional'
1187 ||
$manLevel[$v]=='unidirectional';
1188 if($allow_unid && array_key_exists($v,$unidtable)){
1189 $ct=$this->mConvTable
[$v];
1190 $this->mConvTable
[$v] = array_merge($ct,$unidtable[$v]);
1196 * Parse rules and flags
1199 function parse($variant){
1201 $variant = $this->mConverter
->getPreferredVariant();
1203 $variants = $this->mConverter
->mVariants
;
1204 $this->parseFlags();
1205 $flags = $this->mFlags
;
1207 // convert to specified variant
1208 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1209 if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
1210 if ( in_array( $variant, $flags ) ) // check if current variant in flags
1211 // then convert <text to convert> to current language
1212 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variant );
1213 else { // if current variant no in flags,
1214 // then we check its fallback variants.
1215 $variantFallbacks = $this->mConverter
->getVariantFallbacks($variant);
1216 foreach ( $variantFallbacks as $variantFallback ) {
1217 // if current variant's fallback exist in flags
1218 if ( in_array( $variantFallback, $flags ) ) {
1219 // then convert <text to convert> to fallback language
1220 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
, $variantFallback );
1225 $this->mFlags
= $flags = array('R');
1228 if( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1229 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1230 $this->mRules
= str_replace('=>','=>',$this->mRules
);
1232 $this->parseRules();
1234 $rules = $this->mRules
;
1236 if( count( $this->mBidtable
) == 0 && count( $this->mUnidtable
) == 0 ){
1237 if(in_array('+',$flags) ||
in_array('-',$flags))
1238 // fill all variants if text in -{A/H/-|text} without rules
1239 foreach($this->mConverter
->mVariants
as $v)
1240 $this->mBidtable
[$v] = $rules;
1241 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1242 $this->mFlags
= $flags = array('R');
1245 if( in_array('R',$flags) ) {
1246 // if we don't do content convert, still strip the -{}- tags
1247 $this->mRuleDisplay
= $rules;
1248 } elseif ( in_array('N',$flags) ){
1249 // proces N flag: output current variant name
1250 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[trim($rules)];
1251 } elseif ( in_array('D',$flags) ){
1252 // proces D flag: output rules description
1253 $this->mRuleDisplay
= $this->getRulesDesc();
1254 } elseif ( in_array('H',$flags) ||
in_array('-',$flags) ) {
1255 // proces H,- flag or T only: output nothing
1256 $this->mRuleDisplay
= '';
1257 } elseif ( in_array('S',$flags) ){
1258 $this->mRuleDisplay
= $this->getRuleConvertedStr($variant,
1259 $this->mConverter
->mDoContentConvert
);
1261 $this->mRuleDisplay
= $this->mManualCodeError
;
1264 if ( in_array('T',$flags) ) {
1265 $this->mRuleTitle
= $this->getRuleConvertedStr($variant,
1266 $this->mConverter
->mDoTitleConvert
);
1269 if (in_array('-', $flags))
1270 $this->mRulesAction
='remove';
1271 if (in_array('+', $flags))
1272 $this->mRulesAction
='add';
1274 $this->generateConvTable();
1280 function hasRules(){
1285 * get display text on markup -{...}-
1288 function getDisplay(){
1289 return $this->mRuleDisplay
;
1292 * get converted title
1295 function getTitle(){
1296 return $this->mRuleTitle
;
1300 * return how deal with conversion rules
1303 function getRulesAction(){
1304 return $this->mRulesAction
;
1308 * get conversion table ( bidirectional and unidirectional conversion table )
1311 function getConvTable(){
1312 return $this->mConvTable
;
1316 * get conversion rules string
1319 function getRules(){
1320 return $this->mRules
;
1324 * get conversion flags
1327 function getFlags(){
1328 return $this->mFlags
;