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;
22 var $mUcfirst = false;
26 * @param string $maincode the main language code of this language
27 * @param array $variants the supported variants of this language
28 * @param array $variantfallback the fallback language of each variant
29 * @param array $markup array defining the markup used for manual conversion
30 * @param array $flags array defining the custom strings that maps to the flags
33 function LanguageConverter($langobj, $maincode,
35 $variantfallbacks=array(),
39 $this->mLangObj
= $langobj;
40 $this->mMainLanguageCode
= $maincode;
41 $this->mVariants
= $variants;
42 $this->mVariantFallbacks
= $variantfallbacks;
43 $this->mCacheKey
= $wgDBname . ":conversiontables";
44 $m = array('begin'=>'-{', 'flagsep'=>'|', 'codesep'=>':',
45 'varsep'=>';', 'end'=>'}-');
46 $this->mMarkup
= array_merge($m, $markup);
47 $f = array('A'=>'A', 'T'=>'T');
48 $this->mFlags
= array_merge($f, $flags);
54 function getVariants() {
55 return $this->mVariants
;
59 * in case some variant is not defined in the markup, we need
60 * to have some fallback. for example, in zh, normally people
61 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
62 * when zh-sg is preferred but not defined, we will pick zh-cn
63 * in this case. right now this is only used by zh.
65 * @param string $v the language code of the variant
66 * @return string the code of the fallback language or false if there is no fallback
69 function getVariantFallback($v) {
70 return $this->mVariantFallbacks
[$v];
75 * get preferred language variants.
76 * @return string the preferred language code
79 function getPreferredVariant() {
80 global $wgUser, $wgRequest;
82 if($this->mPreferredVariant
)
83 return $this->mPreferredVariant
;
85 // see if the preference is set in the request
86 $req = $wgRequest->getText( 'variant' );
87 if( in_array( $req, $this->mVariants
) ) {
88 $this->mPreferredVariant
= $req;
92 // get language variant preference from logged in users
93 if(is_object($wgUser) && $wgUser->isLoggedIn() ) {
94 $this->mPreferredVariant
= $wgUser->getOption('variant');
95 return $this->mPreferredVariant
;
98 # FIXME rewrite code for parsing http header. The current code
99 # is written specific for detecting zh- variants
100 if( !$this->mPreferredVariant
) {
101 // see if some supported language variant is set in the
102 // http header, but we don't set the mPreferredVariant
103 // variable in case this is called before the user's
104 // preference is loaded
105 $pv=$this->mMainLanguageCode
;
106 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
107 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
108 $zh = strstr($header, 'zh-');
110 $pv = substr($zh,0,5);
118 * dictionary-based conversion
120 * @param string $text the text to be converted
121 * @param string $toVariant the target language code
122 * @return string the converted text
125 function autoConvert($text, $toVariant=false) {
126 $fname="LanguageConverter::autoConvert";
128 wfProfileIn( $fname );
130 if(!$this->mTablesLoaded
)
134 $toVariant = $this->getPreferredVariant();
135 if(!in_array($toVariant, $this->mVariants
))
138 /* we convert everything except:
139 1. html markups (anything between < and >)
141 3. place holders created by the parser
144 if (isset($wgParser))
145 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
148 $reg = '/<[^>]+>|&[a-z#][a-z0-9]+;' . $marker . '/';
149 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
152 $m = array_shift($matches);
153 $ret = strtr($m[0], $this->mTables
[$toVariant]);
154 $mstart = $m[1]+
strlen($m[0]);
155 foreach($matches as $m) {
156 $ret .= substr($text, $mstart, $m[1]-$mstart);
157 $ret .= strtr($m[0], $this->mTables
[$toVariant]);
158 $mstart = $m[1] +
strlen($m[0]);
160 wfProfileOut( $fname );
165 * convert text to all supported variants
167 * @param string $text the text to be converted
168 * @return array of string
171 function autoConvertToAllVariants($text) {
172 $fname="LanguageConverter::autoConvertToAllVariants";
173 wfProfileIn( $fname );
174 if( !$this->mTablesLoaded
)
178 foreach($this->mVariants
as $variant) {
179 $ret[$variant] = strtr($text, $this->mTables
[$variant]);
181 wfProfileOut( $fname );
186 * Convert text using a parser object for context
188 function parserConvert( $text, &$parser ) {
189 global $wgDisableLangConversion;
190 /* don't do anything if this is the conversion table */
191 if ( $parser->mTitle
->getNamespace() == NS_MEDIAWIKI
&&
192 strpos($parser->mTitle
->getText
, "Conversiontable") !== false )
197 if($wgDisableLangConversion)
200 $text = $this->convert( $text );
201 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
206 * convert text to different variants of a language. the automatic
207 * conversion is done in autoConvert(). here we parse the text
208 * marked with -{}-, which specifies special conversions of the
209 * text that can not be accomplished in autoConvert()
211 * syntax of the markup:
212 * -{code1:text1;code2:text2;...}- or
213 * -{text}- in which case no conversion should take place for text
215 * @param string $text text to be converted
216 * @param bool $isTitle whether this conversion is for the article title
217 * @return string converted text
220 function convert( $text , $isTitle=false) {
221 $mw =& MagicWord
::get( MAG_NOTITLECONVERT
);
222 if( $mw->matchAndRemove( $text ) )
223 $this->mDoTitleConvert
= false;
225 $mw =& MagicWord
::get( MAG_NOCONTENTCONVERT
);
226 if( $mw->matchAndRemove( $text ) ) {
227 $this->mDoContentConvert
= false;
230 // no conversion if redirecting
231 $mw =& MagicWord
::get( MAG_REDIRECT
);
232 if( $mw->matchStart( $text ))
236 if( !$this->mDoTitleConvert
) {
237 $this->mTitleDisplay
= $text;
240 if( !empty($this->mTitleDisplay
))
241 return $this->mTitleDisplay
;
244 $isredir = $wgRequest->getText( 'redirect', 'yes' );
245 $action = $wgRequest->getText( 'action' );
246 if ( $isredir == 'no' ||
$action == 'edit' ) {
250 $this->mTitleDisplay
= $this->autoConvert($text);
251 return $this->mTitleDisplay
;
255 if( !$this->mDoContentConvert
)
258 $plang = $this->getPreferredVariant();
259 if( isset( $this->mVariantFallbacks
[$plang] ) ) {
260 $fallback = $this->mVariantFallbacks
[$plang];
262 // This sounds... bad?
266 $tarray = explode($this->mMarkup
['begin'], $text);
267 $tfirst = array_shift($tarray);
268 $text = $this->autoConvert($tfirst);
269 foreach($tarray as $txt) {
270 $marked = explode($this->mMarkup
['end'], $txt, 2);
272 $tt = explode($this->mMarkup
['flagsep'], $marked[0], 2);
274 if(sizeof($tt) == 2) {
275 $f = explode($this->mMarkup
['varsep'], $tt[0]);
278 if(array_key_exists($ff, $this->mFlags
) &&
279 !array_key_exists($this->mFlags
[$ff], $flags))
280 $flags[] = $this->mFlags
[$ff];
287 #FIXME: may cause trouble here...
288 //strip since it interferes with the parsing, plus,
289 //all spaces should be stripped in this tag anyway.
290 $rules = str_replace(' ', '', $rules);
292 $carray = $this->parseManualRule($rules, $flags);
294 if(array_key_exists($plang, $carray))
295 $disp = $carray[$plang];
296 else if(array_key_exists($fallback, $carray))
297 $disp = $carray[$fallback];
299 if(in_array('T', $flags))
300 $this->mTitleDisplay
= $disp;
304 if(in_array('A', $flags)) {
305 /* modify the conversion table for this session*/
307 /* fill in the missing variants, if any,
309 foreach($this->mVariants
as $v) {
310 if(!array_key_exists($v, $carray)) {
311 $vf = $this->getVariantFallback($v);
312 if(array_key_exists($vf, $carray))
313 $carray[$v] = $carray[$vf];
317 foreach($this->mVariants
as $vfrom) {
318 if(!array_key_exists($vfrom, $carray))
320 foreach($this->mVariants
as $vto) {
323 if(!array_key_exists($vto, $carray))
325 $this->mTables
[$vto][$carray[$vfrom]] = $carray[$vto];
334 if(array_key_exists(1, $marked))
335 $text .= $this->autoConvert($marked[1]);
342 * parse the manually marked conversion rule
343 * @param string $rule the text of the rule
344 * @return array of the translation in each variant
347 function parseManualRule($rules, $flags=array()) {
349 $choice = explode($this->mMarkup
['varsep'], $rules);
351 if(sizeof($choice) == 1) {
352 /* a single choice */
353 foreach($this->mVariants
as $v)
354 $carray[$v] = $choice[0];
357 foreach($choice as $c) {
358 $v = explode($this->mMarkup
['codesep'], $c);
359 if(sizeof($v) != 2) // syntax error, skip
361 $carray[trim($v[0])] = trim($v[1]);
368 * if a language supports multiple variants, it is
369 * possible that non-existing link in one variant
370 * actually exists in another variant. this function
371 * tries to find it. See e.g. LanguageZh.php
373 * @param string $link the name of the link
374 * @param mixed $nt the title object of the link
375 * @return null the input parameters may be modified upon return
378 function findVariantLink( &$link, &$nt ) {
379 static $count=0; //used to limit this operation
380 static $cache=array();
381 global $wgDisableLangConversion;
382 $pref = $this->getPreferredVariant();
385 $ns = $nt->getNamespace();
386 if( $count > 50 && $ns != NS_CATEGORY
)
389 $variants = $this->autoConvertToAllVariants($link);
390 if($variants == false) //give up
392 foreach( $variants as $v ) {
393 if(isset($cache[$v]))
396 $varnt = Title
::newFromText( $v );
397 if( $varnt && $varnt->getArticleID() > 0 ) {
399 if( !$wgDisableLangConversion )
407 * returns language specific hash options
411 function getExtraHashOptions() {
412 $variant = $this->getPreferredVariant();
413 return '!' . $variant ;
417 * get title text as defined in the body of the article text
421 function getParsedTitle() {
422 return $this->mTitleDisplay
;
426 * a write lock to the cache
430 function lockCache() {
433 for($i=0; $i<30; $i++
) {
434 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
446 function unlockCache() {
448 $wgMemc->delete($this->mCacheKey
. "lock");
453 * Load default conversion tables
454 * This method must be implemented in derived class
458 function loadDefaultTables() {
459 $name = get_class($this);
460 wfDie("Must implement loadDefaultTables() method in class $name");
464 * load conversion tables either from the cache or the disk
467 function loadTables($fromcache=true) {
469 if( $this->mTablesLoaded
)
471 $this->mTablesLoaded
= true;
473 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
474 if( !empty( $this->mTables
) ) //all done
477 // not in cache, or we need a fresh reload.
478 // we will first load the default tables
479 // then update them using things in MediaWiki:Zhconversiontable/*
480 global $wgMessageCache;
481 $this->loadDefaultTables();
482 foreach($this->mVariants
as $var) {
483 $cached = $this->parseCachedTable($var);
484 $this->mTables
[$var] = array_merge($this->mTables
[$var], $cached);
487 $this->postLoadTables();
489 if($this->lockCache()) {
490 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
491 $this->unlockCache();
496 * Hook for post processig after conversion tables are loaded
499 function postLoadTables() {}
502 * Reload the conversion tables
506 function reloadTables() {
508 unset($this->mTables
);
509 $this->mTablesLoaded
= false;
510 $this->loadTables(false);
515 * parse the conversion table stored in the cache
517 * the tables should be in blocks of the following form:
525 * to make the tables more manageable, subpages are allowed
526 * and will be parsed recursively if $recursive=true
530 function parseCachedTable($code, $subpage='', $recursive=true) {
531 global $wgMessageCache;
532 static $parsed = array();
534 if(!is_object($wgMessageCache))
537 $key = 'Conversiontable/'.$code;
539 $key .= '/' . $subpage;
541 if(array_key_exists($key, $parsed))
545 $txt = $wgMessageCache->get( $key, true, true, true );
547 // get all subpage links of the form
548 // [[MediaWiki:conversiontable/zh-xx/...|...]]
549 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
550 $subs = explode('[[', $txt);
552 foreach( $subs as $sub ) {
553 $link = explode(']]', $sub, 2);
554 if(count($link) != 2)
556 $b = explode('|', $link[0]);
557 $b = explode('/', trim($b[0]), 3);
563 if($b[0] == $linkhead && $b[1] == $code) {
564 $sublinks[] = $sublink;
569 // parse the mappings in this page
570 $blocks = explode($this->mMarkup
['begin'], $txt);
571 array_shift($blocks);
573 foreach($blocks as $block) {
574 $mappings = explode($this->mMarkup
['end'], $block, 2);
575 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
576 $table = explode( ';', $stripped );
577 foreach( $table as $t ) {
578 $m = explode( '=>', $t );
579 if( count( $m ) != 2)
581 // trim any trailling comments starting with '//'
582 $tt = explode('//', $m[1], 2);
583 $ret[trim($m[0])] = trim($tt[0]);
586 $parsed[$key] = true;
589 // recursively parse the subpages
591 foreach($sublinks as $link) {
592 $s = $this->parseCachedTable($code, $link, $recursive);
593 $ret = array_merge($ret, $s);
597 if ($this->mUcfirst
) {
598 foreach ($ret as $k => $v) {
599 $ret[LanguageUtf8
::ucfirst($k)] = LanguageUtf8
::ucfirst($v);
606 * Enclose a string with the "no conversion" tag. This is used by
607 * various functions in the Parser
609 * @param string $text text to be tagged for no conversion
610 * @return string the tagged text
612 function markNoConversion($text) {
613 # don't mark if already marked
614 if(strpos($text, $this->mMarkup
['begin']) ||
615 strpos($text, $this->mMarkup
['end']))
618 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
623 * convert the sorting key for category links. this should make different
624 * keys that are variants of each other map to the same key
626 function convertCategoryKey( $key ) {
630 * hook to refresh the cache of conversion tables when
631 * MediaWiki:conversiontable* is updated
634 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
635 $titleobj = $article->getTitle();
636 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
638 global $wgContLang; // should be an LanguageZh.
639 if(get_class($wgContLang) != 'languagezh')
642 $title = $titleobj->getDBkey();
643 $t = explode('/', $title, 3);
645 if( $c > 1 && $t[0] == 'Conversiontable' ) {
646 if(in_array($t[1], $this->mVariants
)) {
647 $this->reloadTables();