6 * @author Zhengzhu Feng <zhengzhu@gmail.com>
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
10 class LanguageConverter
{
11 var $mPreferredVariant='';
12 var $mMainLanguageCode;
13 var $mVariants, $mVariantFallbacks;
14 var $mTablesLoaded = false;
16 var $mTitleDisplay='';
17 var $mDoTitleConvert=true, $mDoContentConvert=true;
18 var $mTitleFromFlag = false;
23 var $mUcfirst = false;
27 * @param string $maincode the main language code of this language
28 * @param array $variants the supported variants of this language
29 * @param array $variantfallback the fallback language of each variant
30 * @param array $markup array defining the markup used for manual conversion
31 * @param array $flags array defining the custom strings that maps to the flags
34 function __construct($langobj, $maincode,
36 $variantfallbacks=array(),
39 global $wgLegalTitleChars;
40 $this->mLangObj
= $langobj;
41 $this->mMainLanguageCode
= $maincode;
42 $this->mVariants
= $variants;
43 $this->mVariantFallbacks
= $variantfallbacks;
44 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
45 $m = array('begin'=>'-{', 'flagsep'=>'|', 'codesep'=>':',
46 'varsep'=>';', 'end'=>'}-');
47 $this->mMarkup
= array_merge($m, $markup);
48 $f = array('A'=>'A', 'T'=>'T');
49 $this->mFlags
= array_merge($f, $flags);
55 function getVariants() {
56 return $this->mVariants
;
60 * in case some variant is not defined in the markup, we need
61 * to have some fallback. for example, in zh, normally people
62 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
63 * when zh-sg is preferred but not defined, we will pick zh-cn
64 * in this case. right now this is only used by zh.
66 * @param string $v the language code of the variant
67 * @return string the code of the fallback language or false if there is no fallback
70 function getVariantFallback($v) {
71 return $this->mVariantFallbacks
[$v];
76 * get preferred language variants.
77 * @param boolean $fromUser Get it from $wgUser's preferences
78 * @return string the preferred language code
81 function getPreferredVariant( $fromUser = true ) {
82 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
84 if($this->mPreferredVariant
)
85 return $this->mPreferredVariant
;
87 // see if the preference is set in the request
88 $req = $wgRequest->getText( 'variant' );
89 if( in_array( $req, $this->mVariants
) ) {
90 $this->mPreferredVariant
= $req;
94 // check the syntax /code/ArticleTitle
95 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
96 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
97 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
98 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
99 if(in_array($scriptBase,$this->mVariants
)){
100 $this->mPreferredVariant
= $scriptBase;
101 return $this->mPreferredVariant
;
105 // get language variant preference from logged in users
106 // Don't call this on stub objects because that causes infinite
107 // recursion during initialisation
108 if( $fromUser && $wgUser->isLoggedIn() ) {
109 $this->mPreferredVariant
= $wgUser->getOption('variant');
110 return $this->mPreferredVariant
;
113 // see if default variant is globaly set
114 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
115 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
116 return $this->mPreferredVariant
;
119 # FIXME rewrite code for parsing http header. The current code
120 # is written specific for detecting zh- variants
121 if( !$this->mPreferredVariant
) {
122 // see if some supported language variant is set in the
123 // http header, but we don't set the mPreferredVariant
124 // variable in case this is called before the user's
125 // preference is loaded
126 $pv=$this->mMainLanguageCode
;
127 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
128 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
129 $zh = strstr($header, $pv.'-');
131 $pv = substr($zh,0,5);
134 // don't try to return bad variant
135 if(in_array( $pv, $this->mVariants
))
139 return $this->mMainLanguageCode
;
144 * dictionary-based conversion
146 * @param string $text the text to be converted
147 * @param string $toVariant the target language code
148 * @return string the converted text
151 function autoConvert($text, $toVariant=false) {
152 $fname="LanguageConverter::autoConvert";
154 wfProfileIn( $fname );
156 if(!$this->mTablesLoaded
)
160 $toVariant = $this->getPreferredVariant();
161 if(!in_array($toVariant, $this->mVariants
))
164 /* we convert everything except:
165 1. html markups (anything between < and >)
167 3. place holders created by the parser
170 if (isset($wgParser))
171 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
175 // this one is needed when the text is inside an html markup
176 $htmlfix = '|<[^>]+$|^[^<>]*>';
178 // disable convert to variants between <code></code> tags
179 $codefix = '<code>.+?<\/code>|';
180 // disable convertsion of <script type="text/javascript"> ... </script>
181 $scriptfix = '<script.*?>.*?<\/script>|';
183 $reg = '/'.$codefix . $scriptfix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
185 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
187 $m = array_shift($matches);
189 $ret = $this->translate($m[0], $toVariant);
190 $mstart = $m[1]+
strlen($m[0]);
191 foreach($matches as $m) {
192 $ret .= substr($text, $mstart, $m[1]-$mstart);
193 $ret .= $this->translate($m[0], $toVariant);
194 $mstart = $m[1] +
strlen($m[0]);
196 wfProfileOut( $fname );
201 * Translate a string to a variant
202 * Doesn't process markup or do any of that other stuff, for that use convert()
204 * @param string $text Text to convert
205 * @param string $variant Variant language code
206 * @return string Translated text
208 function translate( $text, $variant ) {
209 wfProfileIn( __METHOD__
);
210 if( !$this->mTablesLoaded
)
212 $text = $this->mTables
[$variant]->replace( $text );
213 wfProfileOut( __METHOD__
);
218 * convert text to all supported variants
220 * @param string $text the text to be converted
221 * @return array of string
224 function autoConvertToAllVariants($text) {
225 $fname="LanguageConverter::autoConvertToAllVariants";
226 wfProfileIn( $fname );
227 if( !$this->mTablesLoaded
)
231 foreach($this->mVariants
as $variant) {
232 $ret[$variant] = $this->translate($text, $variant);
235 wfProfileOut( $fname );
240 * convert link text to all supported variants
242 * @param string $text the text to be converted
243 * @return array of string
246 function convertLinkToAllVariants($text) {
247 if( !$this->mTablesLoaded
)
251 $tarray = explode($this->mMarkup
['begin'], $text);
252 $tfirst = array_shift($tarray);
254 foreach($this->mVariants
as $variant)
255 $ret[$variant] = $this->translate($tfirst,$variant);
257 foreach($tarray as $txt) {
258 $marked = explode($this->mMarkup
['end'], $txt, 2);
260 foreach($this->mVariants
as $variant){
261 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
262 if(array_key_exists(1, $marked))
263 $ret[$variant] .= $this->translate($marked[1],$variant);
273 * Convert text using a parser object for context
275 function parserConvert( $text, &$parser ) {
276 global $wgDisableLangConversion;
277 /* don't do anything if this is the conversion table */
278 if ( $parser->mTitle
->getNamespace() == NS_MEDIAWIKI
&&
279 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
284 if($wgDisableLangConversion)
287 $text = $this->convert( $text );
288 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
293 * Parse flags with syntax -{FLAG| ... }-
296 function parseFlags($marked){
299 // process flag only if the flag is valid
300 if(! ( in_array($marked[0],$this->mFlags
) && $marked[1]=='|' ) )
301 return array($marked,array());
303 $tt = explode($this->mMarkup
['flagsep'], $marked, 2);
305 if(sizeof($tt) == 2) {
306 $f = explode($this->mMarkup
['varsep'], $tt[0]);
309 if(array_key_exists($ff, $this->mFlags
) &&
310 !array_key_exists($this->mFlags
[$ff], $flags))
311 $flags[] = $this->mFlags
[$ff];
318 //FIXME: may cause trouble here...
319 //strip since it interferes with the parsing, plus,
320 //all spaces should be stripped in this tag anyway.
321 $rules = str_replace(' ', '', $rules);
323 return array($rules,$flags);
327 * convert text to different variants of a language. the automatic
328 * conversion is done in autoConvert(). here we parse the text
329 * marked with -{}-, which specifies special conversions of the
330 * text that can not be accomplished in autoConvert()
332 * syntax of the markup:
333 * -{code1:text1;code2:text2;...}- or
334 * -{text}- in which case no conversion should take place for text
336 * @param string $text text to be converted
337 * @param bool $isTitle whether this conversion is for the article title
338 * @return string converted text
341 function convert( $text , $isTitle=false) {
342 $mw =& MagicWord
::get( 'notitleconvert' );
343 if( $mw->matchAndRemove( $text ) )
344 $this->mDoTitleConvert
= false;
346 $mw =& MagicWord
::get( 'nocontentconvert' );
347 if( $mw->matchAndRemove( $text ) ) {
348 $this->mDoContentConvert
= false;
351 // no conversion if redirecting
352 $mw =& MagicWord
::get( 'redirect' );
353 if( $mw->matchStart( $text ))
358 // use the title from the T flag if any
359 if($this->mTitleFromFlag
){
360 $this->mTitleFromFlag
= false;
361 return $this->mTitleDisplay
;
364 // check for __NOTC__ tag
365 if( !$this->mDoTitleConvert
) {
366 $this->mTitleDisplay
= $text;
371 $isredir = $wgRequest->getText( 'redirect', 'yes' );
372 $action = $wgRequest->getText( 'action' );
373 if ( $isredir == 'no' ||
$action == 'edit' ) {
377 $this->mTitleDisplay
= $this->convert($text);
378 return $this->mTitleDisplay
;
382 $plang = $this->getPreferredVariant();
383 if( isset( $this->mVariantFallbacks
[$plang] ) ) {
384 $fallback = $this->mVariantFallbacks
[$plang];
386 $fallback = $this->mMainLanguageCode
;
389 $tarray = explode($this->mMarkup
['begin'], $text);
390 $tfirst = array_shift($tarray);
391 if($this->mDoContentConvert
)
392 $text = $this->autoConvert($tfirst);
395 foreach($tarray as $txt) {
396 $marked = explode($this->mMarkup
['end'], $txt, 2);
398 // strip the flags from syntax like -{T| ... }-
399 list($rules,$flags) = $this->parseFlags($marked[0]);
401 if( $this->mDoContentConvert
){
402 // parse the contents -{ ... }-
403 $carray = $this->parseManualRule($rules, $flags);
406 if(array_key_exists($plang, $carray))
407 $disp = $carray[$plang];
408 else if(array_key_exists($fallback, $carray))
409 $disp = $carray[$fallback];
411 // if we don't do content convert, still strip the -{}- tags
417 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
418 if(in_array('T', $flags)){
419 $this->mTitleFromFlag
= true;
420 $this->mTitleDisplay
= $disp;
425 // use syntax -{A|zh:WordZh;zh-tw:WordTw}- to introduce a custom mapping between
426 // words WordZh and WordTw in the whole text
427 if(in_array('A', $flags)) {
429 /* fill in the missing variants, if any,
431 foreach($this->mVariants
as $v) {
432 if(!array_key_exists($v, $carray)) {
433 $vf = $this->getVariantFallback($v);
434 if(array_key_exists($vf, $carray))
435 $carray[$v] = $carray[$vf];
439 foreach($this->mVariants
as $vfrom) {
440 if(!array_key_exists($vfrom, $carray))
442 foreach($this->mVariants
as $vto) {
445 if(!array_key_exists($vto, $carray))
447 $this->mTables
[$vto]->setPair($carray[$vfrom], $carray[$vto]);
455 if(array_key_exists(1, $marked)){
456 if( $this->mDoContentConvert
)
457 $text .= $this->autoConvert($marked[1]);
467 * parse the manually marked conversion rule
468 * @param string $rule the text of the rule
469 * @return array of the translation in each variant
472 function parseManualRule($rules, $flags=array()) {
474 $choice = explode($this->mMarkup
['varsep'], $rules);
476 if(sizeof($choice) == 1) {
477 /* a single choice */
478 foreach($this->mVariants
as $v)
479 $carray[$v] = $choice[0];
482 foreach($choice as $c) {
483 $v = explode($this->mMarkup
['codesep'], $c);
484 if(sizeof($v) != 2) // syntax error, skip
486 $carray[trim($v[0])] = trim($v[1]);
493 * if a language supports multiple variants, it is
494 * possible that non-existing link in one variant
495 * actually exists in another variant. this function
496 * tries to find it. See e.g. LanguageZh.php
498 * @param string $link the name of the link
499 * @param mixed $nt the title object of the link
500 * @return null the input parameters may be modified upon return
503 function findVariantLink( &$link, &$nt ) {
504 global $wgDisableLangConversion;
505 $linkBatch = new LinkBatch();
510 $ns = $nt->getNamespace();
512 $variants = $this->autoConvertToAllVariants($link);
513 if($variants == false) //give up
518 foreach( $variants as $v ) {
520 $varnt = Title
::newFromText( $v, $ns );
521 if(!is_null($varnt)){
522 $linkBatch->addObj($varnt);
528 // fetch all variants in single query
529 $linkBatch->execute();
531 foreach( $titles as $varnt ) {
532 if( $varnt->getArticleID() > 0 ) {
534 if( !$wgDisableLangConversion )
542 * returns language specific hash options
546 function getExtraHashOptions() {
547 $variant = $this->getPreferredVariant();
548 return '!' . $variant ;
552 * get title text as defined in the body of the article text
556 function getParsedTitle() {
557 return $this->mTitleDisplay
;
561 * a write lock to the cache
565 function lockCache() {
568 for($i=0; $i<30; $i++
) {
569 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
581 function unlockCache() {
583 $wgMemc->delete($this->mCacheKey
. "lock");
588 * Load default conversion tables
589 * This method must be implemented in derived class
593 function loadDefaultTables() {
594 $name = get_class($this);
595 wfDie("Must implement loadDefaultTables() method in class $name");
599 * load conversion tables either from the cache or the disk
602 function loadTables($fromcache=true) {
604 if( $this->mTablesLoaded
)
606 wfProfileIn( __METHOD__
);
607 $this->mTablesLoaded
= true;
608 $this->mTables
= false;
610 wfProfileIn( __METHOD__
.'-cache' );
611 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
612 wfProfileOut( __METHOD__
.'-cache' );
614 if ( !$this->mTables ||
!isset( $this->mTables
['VERSION 2'] ) ) {
615 wfProfileIn( __METHOD__
.'-recache' );
616 // not in cache, or we need a fresh reload.
617 // we will first load the default tables
618 // then update them using things in MediaWiki:Zhconversiontable/*
619 global $wgMessageCache;
620 $this->loadDefaultTables();
621 foreach($this->mVariants
as $var) {
622 $cached = $this->parseCachedTable($var);
623 $this->mTables
[$var]->mergeArray($cached);
626 $this->postLoadTables();
627 $this->mTables
['VERSION 2'] = true;
629 if($this->lockCache()) {
630 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
631 $this->unlockCache();
633 wfProfileOut( __METHOD__
.'-recache' );
635 wfProfileOut( __METHOD__
);
639 * Hook for post processig after conversion tables are loaded
642 function postLoadTables() {}
645 * Reload the conversion tables
649 function reloadTables() {
651 unset($this->mTables
);
652 $this->mTablesLoaded
= false;
653 $this->loadTables(false);
658 * parse the conversion table stored in the cache
660 * the tables should be in blocks of the following form:
668 * to make the tables more manageable, subpages are allowed
669 * and will be parsed recursively if $recursive=true
673 function parseCachedTable($code, $subpage='', $recursive=true) {
674 global $wgMessageCache;
675 static $parsed = array();
677 if(!is_object($wgMessageCache))
680 $key = 'Conversiontable/'.$code;
682 $key .= '/' . $subpage;
684 if(array_key_exists($key, $parsed))
688 $txt = $wgMessageCache->get( $key, true, true, true );
690 // get all subpage links of the form
691 // [[MediaWiki:conversiontable/zh-xx/...|...]]
692 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
693 $subs = explode('[[', $txt);
695 foreach( $subs as $sub ) {
696 $link = explode(']]', $sub, 2);
697 if(count($link) != 2)
699 $b = explode('|', $link[0]);
700 $b = explode('/', trim($b[0]), 3);
706 if($b[0] == $linkhead && $b[1] == $code) {
707 $sublinks[] = $sublink;
712 // parse the mappings in this page
713 $blocks = explode($this->mMarkup
['begin'], $txt);
714 array_shift($blocks);
716 foreach($blocks as $block) {
717 $mappings = explode($this->mMarkup
['end'], $block, 2);
718 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
719 $table = explode( ';', $stripped );
720 foreach( $table as $t ) {
721 $m = explode( '=>', $t );
722 if( count( $m ) != 2)
724 // trim any trailling comments starting with '//'
725 $tt = explode('//', $m[1], 2);
726 $ret[trim($m[0])] = trim($tt[0]);
729 $parsed[$key] = true;
732 // recursively parse the subpages
734 foreach($sublinks as $link) {
735 $s = $this->parseCachedTable($code, $link, $recursive);
736 $ret = array_merge($ret, $s);
740 if ($this->mUcfirst
) {
741 foreach ($ret as $k => $v) {
742 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
749 * Enclose a string with the "no conversion" tag. This is used by
750 * various functions in the Parser
752 * @param string $text text to be tagged for no conversion
753 * @return string the tagged text
755 function markNoConversion($text, $noParse=false) {
756 # don't mark if already marked
757 if(strpos($text, $this->mMarkup
['begin']) ||
758 strpos($text, $this->mMarkup
['end']))
761 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
766 * convert the sorting key for category links. this should make different
767 * keys that are variants of each other map to the same key
769 function convertCategoryKey( $key ) {
773 * hook to refresh the cache of conversion tables when
774 * MediaWiki:conversiontable* is updated
777 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
778 $titleobj = $article->getTitle();
779 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
781 global $wgContLang; // should be an LanguageZh.
782 if(get_class($wgContLang) != 'languagezh')
785 $title = $titleobj->getDBkey();
786 $t = explode('/', $title, 3);
788 if( $c > 1 && $t[0] == 'Conversiontable' ) {
789 if(in_array($t[1], $this->mVariants
)) {
790 $this->reloadTables();
798 * Armour rendered math against conversion
799 * Default is do nothing, since the process can interfere with
800 * parseManualRule() if format -{ alter1 ; alter2 }- is enabled
802 function armourMath($text){