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;
18 var $mTitleDisplay='';
19 var $mDoTitleConvert=true, $mDoContentConvert=true;
24 var $mUcfirst = false;
25 var $mNoTitleConvert = false;
29 * @param string $maincode the main language code of this language
30 * @param array $variants the supported variants of this language
31 * @param array $variantfallback the fallback language of each variant
32 * @param array $markup array defining the markup used for manual conversion
33 * @param array $flags array defining the custom strings that maps to the flags
36 function __construct($langobj, $maincode,
38 $variantfallbacks=array(),
41 global $wgLegalTitleChars;
42 $this->mLangObj
= $langobj;
43 $this->mMainLanguageCode
= $maincode;
44 $this->mVariants
= $variants;
45 $this->mVariantFallbacks
= $variantfallbacks;
46 $this->mCacheKey
= wfMemcKey( 'conversiontables' );
47 $m = array('begin'=>'-{', 'flagsep'=>'|', 'codesep'=>':',
48 'varsep'=>';', 'end'=>'}-');
49 $this->mMarkup
= array_merge($m, $markup);
50 $f = array('A'=>'A', 'T'=>'T');
51 $this->mFlags
= array_merge($f, $flags);
52 if ( function_exists( 'fss_prep_replace' ) ) {
53 $this->mUseFss
= true;
60 function getVariants() {
61 return $this->mVariants
;
65 * in case some variant is not defined in the markup, we need
66 * to have some fallback. for example, in zh, normally people
67 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
68 * when zh-sg is preferred but not defined, we will pick zh-cn
69 * in this case. right now this is only used by zh.
71 * @param string $v the language code of the variant
72 * @return string the code of the fallback language or false if there is no fallback
75 function getVariantFallback($v) {
76 return $this->mVariantFallbacks
[$v];
81 * get preferred language variants.
82 * @param boolean $fromUser Get it from $wgUser's preferences
83 * @return string the preferred language code
86 function getPreferredVariant( $fromUser = true ) {
87 global $wgUser, $wgRequest;
89 if($this->mPreferredVariant
)
90 return $this->mPreferredVariant
;
92 // see if the preference is set in the request
93 $req = $wgRequest->getText( 'variant' );
94 if( in_array( $req, $this->mVariants
) ) {
95 $this->mPreferredVariant
= $req;
99 // check the syntax /code/ArticleTitle
100 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
101 if(in_array($scriptBase,$this->mVariants
)){
102 $this->mPreferredVariant
= $scriptBase;
103 return $this->mPreferredVariant
;
106 // get language variant preference from logged in users
107 // Don't call this on stub objects because that causes infinite
108 // recursion during initialisation
109 if( $fromUser && $wgUser->isLoggedIn() ) {
110 $this->mPreferredVariant
= $wgUser->getOption('variant');
111 return $this->mPreferredVariant
;
114 # FIXME rewrite code for parsing http header. The current code
115 # is written specific for detecting zh- variants
116 if( !$this->mPreferredVariant
) {
117 // see if some supported language variant is set in the
118 // http header, but we don't set the mPreferredVariant
119 // variable in case this is called before the user's
120 // preference is loaded
121 $pv=$this->mMainLanguageCode
;
122 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
123 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
124 $zh = strstr($header, 'zh-');
126 $pv = substr($zh,0,5);
134 * dictionary-based conversion
136 * @param string $text the text to be converted
137 * @param string $toVariant the target language code
138 * @return string the converted text
141 function autoConvert($text, $toVariant=false) {
142 $fname="LanguageConverter::autoConvert";
144 wfProfileIn( $fname );
146 if(!$this->mTablesLoaded
)
150 $toVariant = $this->getPreferredVariant();
151 if(!in_array($toVariant, $this->mVariants
))
154 /* we convert everything except:
155 1. html markups (anything between < and >)
157 3. place holders created by the parser
160 if (isset($wgParser))
161 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
165 // this one is needed when the text is inside an html markup
166 $htmlfix = '|<[^>]+$|^[^<>]*>';
168 // disable convert to variants between <code></code> tags
169 $codefix = '<code>.+?<\/code>|';
171 $reg = '/'.$codefix.'<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
173 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
175 $m = array_shift($matches);
177 $ret = $this->translate($m[0], $toVariant);
178 $mstart = $m[1]+
strlen($m[0]);
179 foreach($matches as $m) {
180 $ret .= substr($text, $mstart, $m[1]-$mstart);
181 $ret .= $this->translate($m[0], $toVariant);
182 $mstart = $m[1] +
strlen($m[0]);
184 wfProfileOut( $fname );
189 * Translate a string to a variant
190 * Doesn't process markup or do any of that other stuff, for that use convert()
192 * @param string $text Text to convert
193 * @param string $variant Variant language code
194 * @return string Translated text
196 function translate( $text, $variant ) {
197 if( !$this->mTablesLoaded
)
199 if ( $this->mUseFss
) {
200 wfProfileIn( __METHOD__
.'-fss' );
201 $text = fss_exec_replace( $this->mFssObjects
[$variant], $text );
202 wfProfileOut( __METHOD__
.'-fss' );
205 wfProfileIn( __METHOD__
.'-strtr' );
206 $text = strtr( $text, $this->mTables
[$variant] );
207 wfProfileOut( __METHOD__
.'-strtr' );
213 * convert text to all supported variants
215 * @param string $text the text to be converted
216 * @return array of string
219 function autoConvertToAllVariants($text) {
220 $fname="LanguageConverter::autoConvertToAllVariants";
221 wfProfileIn( $fname );
222 if( !$this->mTablesLoaded
)
226 foreach($this->mVariants
as $variant) {
227 $ret[$variant] = $this->translate($text, $variant);
230 wfProfileOut( $fname );
235 * convert link text to all supported variants
237 * @param string $text the text to be converted
238 * @return array of string
241 function convertLinkToAllVariants($text) {
242 if( !$this->mTablesLoaded
)
246 $tarray = explode($this->mMarkup
['begin'], $text);
247 $tfirst = array_shift($tarray);
249 foreach($this->mVariants
as $variant)
250 $ret[$variant] = $this->translate($tfirst,$variant);
252 foreach($tarray as $txt) {
253 $marked = explode($this->mMarkup
['end'], $txt, 2);
255 foreach($this->mVariants
as $variant){
256 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
257 if(array_key_exists(1, $marked))
258 $ret[$variant] .= $this->translate($marked[1],$variant);
268 * Convert text using a parser object for context
270 function parserConvert( $text, &$parser ) {
271 global $wgDisableLangConversion;
272 /* don't do anything if this is the conversion table */
273 if ( $parser->mTitle
->getNamespace() == NS_MEDIAWIKI
&&
274 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
279 if($wgDisableLangConversion)
282 $text = $this->convert( $text );
283 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
288 * convert text to different variants of a language. the automatic
289 * conversion is done in autoConvert(). here we parse the text
290 * marked with -{}-, which specifies special conversions of the
291 * text that can not be accomplished in autoConvert()
293 * syntax of the markup:
294 * -{code1:text1;code2:text2;...}- or
295 * -{text}- in which case no conversion should take place for text
297 * @param string $text text to be converted
298 * @param bool $isTitle whether this conversion is for the article title
299 * @return string converted text
302 function convert( $text , $isTitle=false) {
303 $mw =& MagicWord
::get( 'notitleconvert' );
304 if( $mw->matchAndRemove( $text ) )
305 $this->mDoTitleConvert
= false;
307 $mw =& MagicWord
::get( 'nocontentconvert' );
308 if( $mw->matchAndRemove( $text ) ) {
309 $this->mDoContentConvert
= false;
312 // no conversion if redirecting
313 $mw =& MagicWord
::get( 'redirect' );
314 if( $mw->matchStart( $text ))
318 if($this->mNoTitleConvert
){
319 $this->mTitleDisplay
= $text;
323 if( !$this->mDoTitleConvert
) {
324 $this->mTitleDisplay
= $text;
329 $isredir = $wgRequest->getText( 'redirect', 'yes' );
330 $action = $wgRequest->getText( 'action' );
331 if ( $isredir == 'no' ||
$action == 'edit' ) {
335 $this->mTitleDisplay
= $this->convert($text);
336 return $this->mTitleDisplay
;
340 if( !$this->mDoContentConvert
)
343 $plang = $this->getPreferredVariant();
344 if( isset( $this->mVariantFallbacks
[$plang] ) ) {
345 $fallback = $this->mVariantFallbacks
[$plang];
347 // This sounds... bad?
351 $tarray = explode($this->mMarkup
['begin'], $text);
352 $tfirst = array_shift($tarray);
353 $text = $this->autoConvert($tfirst);
354 foreach($tarray as $txt) {
355 $marked = explode($this->mMarkup
['end'], $txt, 2);
357 $tt = explode($this->mMarkup
['flagsep'], $marked[0], 2);
359 if(sizeof($tt) == 2) {
360 $f = explode($this->mMarkup
['varsep'], $tt[0]);
363 if(array_key_exists($ff, $this->mFlags
) &&
364 !array_key_exists($this->mFlags
[$ff], $flags))
365 $flags[] = $this->mFlags
[$ff];
372 //FIXME: may cause trouble here...
373 //strip since it interferes with the parsing, plus,
374 //all spaces should be stripped in this tag anyway.
375 $rules = str_replace(' ', '', $rules);
377 $carray = $this->parseManualRule($rules, $flags);
379 if(array_key_exists($plang, $carray))
380 $disp = $carray[$plang];
381 else if(array_key_exists($fallback, $carray))
382 $disp = $carray[$fallback];
384 if(in_array('T', $flags))
385 $this->mTitleDisplay
= $disp;
389 if(in_array('A', $flags)) {
390 /* modify the conversion table for this session*/
392 /* fill in the missing variants, if any,
394 foreach($this->mVariants
as $v) {
395 if(!array_key_exists($v, $carray)) {
396 $vf = $this->getVariantFallback($v);
397 if(array_key_exists($vf, $carray))
398 $carray[$v] = $carray[$vf];
402 foreach($this->mVariants
as $vfrom) {
403 if(!array_key_exists($vfrom, $carray))
405 foreach($this->mVariants
as $vto) {
408 if(!array_key_exists($vto, $carray))
410 $this->mTables
[$vto][$carray[$vfrom]] = $carray[$vto];
414 if ( $this->mUseFss
) {
415 $this->generateFssObjects();
422 if(array_key_exists(1, $marked))
423 $text .= $this->autoConvert($marked[1]);
430 * parse the manually marked conversion rule
431 * @param string $rule the text of the rule
432 * @return array of the translation in each variant
435 function parseManualRule($rules, $flags=array()) {
437 $choice = explode($this->mMarkup
['varsep'], $rules);
439 if(sizeof($choice) == 1) {
440 /* a single choice */
441 foreach($this->mVariants
as $v)
442 $carray[$v] = $choice[0];
445 foreach($choice as $c) {
446 $v = explode($this->mMarkup
['codesep'], $c);
447 if(sizeof($v) != 2) // syntax error, skip
449 $carray[trim($v[0])] = trim($v[1]);
456 * if a language supports multiple variants, it is
457 * possible that non-existing link in one variant
458 * actually exists in another variant. this function
459 * tries to find it. See e.g. LanguageZh.php
461 * @param string $link the name of the link
462 * @param mixed $nt the title object of the link
463 * @return null the input parameters may be modified upon return
466 function findVariantLink( &$link, &$nt ) {
467 global $wgDisableLangConversion;
468 $pref = $this->getPreferredVariant();
471 $ns = $nt->getNamespace();
473 $variants = $this->autoConvertToAllVariants($link);
474 if($variants == false) //give up
476 foreach( $variants as $v ) {
477 $varnt = Title
::newFromText( $v, $ns );
478 if( $varnt && $varnt->getArticleID() > 0 ) {
480 if( !$wgDisableLangConversion )
488 * returns language specific hash options
492 function getExtraHashOptions() {
493 $variant = $this->getPreferredVariant();
494 return '!' . $variant ;
498 * get title text as defined in the body of the article text
502 function getParsedTitle() {
503 return $this->mTitleDisplay
;
507 * a write lock to the cache
511 function lockCache() {
514 for($i=0; $i<30; $i++
) {
515 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
527 function unlockCache() {
529 $wgMemc->delete($this->mCacheKey
. "lock");
534 * Load default conversion tables
535 * This method must be implemented in derived class
539 function loadDefaultTables() {
540 $name = get_class($this);
541 wfDie("Must implement loadDefaultTables() method in class $name");
545 * load conversion tables either from the cache or the disk
548 function loadTables($fromcache=true) {
550 if( $this->mTablesLoaded
)
552 wfProfileIn( __METHOD__
);
553 $this->mTablesLoaded
= true;
554 $this->mTables
= false;
556 wfProfileIn( __METHOD__
.'-cache' );
557 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
558 wfProfileOut( __METHOD__
.'-cache' );
560 if ( !$this->mTables
) {
561 wfProfileOut( __METHOD__
.'-recache' );
562 // not in cache, or we need a fresh reload.
563 // we will first load the default tables
564 // then update them using things in MediaWiki:Zhconversiontable/*
565 global $wgMessageCache;
566 $this->loadDefaultTables();
567 foreach($this->mVariants
as $var) {
568 $cached = $this->parseCachedTable($var);
569 $this->mTables
[$var] = array_merge($this->mTables
[$var], $cached);
572 $this->postLoadTables();
574 if($this->lockCache()) {
575 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
576 $this->unlockCache();
578 wfProfileOut( __METHOD__
.'-recache' );
580 if ( $this->mUseFss
) {
581 wfProfileIn( __METHOD__
.'-fss' );
582 $this->generateFssObjects();
583 wfProfileOut( __METHOD__
.'-fss' );
585 wfProfileOut( __METHOD__
);
589 * Generate FSS objects. The FSS extension must be available.
591 function generateFssObjects() {
592 foreach ( $this->mTables
as $variant => $table ) {
593 $this->mFssObjects
[$variant] = fss_prep_replace( $table );
598 * Hook for post processig after conversion tables are loaded
601 function postLoadTables() {}
604 * Reload the conversion tables
608 function reloadTables() {
610 unset($this->mTables
);
611 $this->mTablesLoaded
= false;
612 $this->loadTables(false);
617 * parse the conversion table stored in the cache
619 * the tables should be in blocks of the following form:
627 * to make the tables more manageable, subpages are allowed
628 * and will be parsed recursively if $recursive=true
632 function parseCachedTable($code, $subpage='', $recursive=true) {
633 global $wgMessageCache;
634 static $parsed = array();
636 if(!is_object($wgMessageCache))
639 $key = 'Conversiontable/'.$code;
641 $key .= '/' . $subpage;
643 if(array_key_exists($key, $parsed))
647 $txt = $wgMessageCache->get( $key, true, true, true );
649 // get all subpage links of the form
650 // [[MediaWiki:conversiontable/zh-xx/...|...]]
651 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
652 $subs = explode('[[', $txt);
654 foreach( $subs as $sub ) {
655 $link = explode(']]', $sub, 2);
656 if(count($link) != 2)
658 $b = explode('|', $link[0]);
659 $b = explode('/', trim($b[0]), 3);
665 if($b[0] == $linkhead && $b[1] == $code) {
666 $sublinks[] = $sublink;
671 // parse the mappings in this page
672 $blocks = explode($this->mMarkup
['begin'], $txt);
673 array_shift($blocks);
675 foreach($blocks as $block) {
676 $mappings = explode($this->mMarkup
['end'], $block, 2);
677 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
678 $table = explode( ';', $stripped );
679 foreach( $table as $t ) {
680 $m = explode( '=>', $t );
681 if( count( $m ) != 2)
683 // trim any trailling comments starting with '//'
684 $tt = explode('//', $m[1], 2);
685 $ret[trim($m[0])] = trim($tt[0]);
688 $parsed[$key] = true;
691 // recursively parse the subpages
693 foreach($sublinks as $link) {
694 $s = $this->parseCachedTable($code, $link, $recursive);
695 $ret = array_merge($ret, $s);
699 if ($this->mUcfirst
) {
700 foreach ($ret as $k => $v) {
701 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
708 * Enclose a string with the "no conversion" tag. This is used by
709 * various functions in the Parser
711 * @param string $text text to be tagged for no conversion
712 * @return string the tagged text
714 function markNoConversion($text, $noParse=false) {
715 # don't mark if already marked
716 if(strpos($text, $this->mMarkup
['begin']) ||
717 strpos($text, $this->mMarkup
['end']))
720 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
725 * convert the sorting key for category links. this should make different
726 * keys that are variants of each other map to the same key
728 function convertCategoryKey( $key ) {
732 * hook to refresh the cache of conversion tables when
733 * MediaWiki:conversiontable* is updated
736 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
737 $titleobj = $article->getTitle();
738 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
740 global $wgContLang; // should be an LanguageZh.
741 if(get_class($wgContLang) != 'languagezh')
744 $title = $titleobj->getDBkey();
745 $t = explode('/', $title, 3);
747 if( $c > 1 && $t[0] == 'Conversiontable' ) {
748 if(in_array($t[1], $this->mVariants
)) {
749 $this->reloadTables();
756 function setNoTitleConvert(){
757 $this->mNoTitleConvert
= true;