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 $fallback = $this->mVariantFallbacks
[$plang];
261 $tarray = explode($this->mMarkup
['begin'], $text);
262 $tfirst = array_shift($tarray);
263 $text = $this->autoConvert($tfirst);
264 foreach($tarray as $txt) {
265 $marked = explode($this->mMarkup
['end'], $txt);
267 $tt = explode($this->mMarkup
['flagsep'], $marked[0], 2);
269 if(sizeof($tt) == 2) {
270 $f = explode($this->mMarkup
['varsep'], $tt[0]);
273 if(array_key_exists($ff, $this->mFlags
) &&
274 !array_key_exists($this->mFlags
[$ff], $flags))
275 $flags[] = $this->mFlags
[$ff];
282 #FIXME: may cause trouble here...
283 //strip since it interferes with the parsing, plus,
284 //all spaces should be stripped in this tag anyway.
285 $rules = str_replace(' ', '', $rules);
287 $carray = $this->parseManualRule($rules, $flags);
289 if(array_key_exists($plang, $carray))
290 $disp = $carray[$plang];
291 else if(array_key_exists($fallback, $carray))
292 $disp = $carray[$fallback];
294 if(in_array('T', $flags))
295 $this->mTitleDisplay
= $disp;
299 if(in_array('A', $flags)) {
300 /* modify the conversion table for this session*/
302 /* fill in the missing variants, if any,
304 foreach($this->mVariants
as $v) {
305 if(!array_key_exists($v, $carray)) {
306 $vf = $this->getVariantFallback($v);
307 if(array_key_exists($vf, $carray))
308 $carray[$v] = $carray[$vf];
312 foreach($this->mVariants
as $vfrom) {
313 if(!array_key_exists($vfrom, $carray))
315 foreach($this->mVariants
as $vto) {
318 if(!array_key_exists($vto, $carray))
320 $this->mTables
[$vto][$carray[$vfrom]] = $carray[$vto];
329 if(array_key_exists(1, $marked))
330 $text .= $this->autoConvert($marked[1]);
337 * parse the manually marked conversion rule
338 * @param string $rule the text of the rule
339 * @return array of the translation in each variant
342 function parseManualRule($rules, $flags=array()) {
344 $choice = explode($this->mMarkup
['varsep'], $rules);
346 if(sizeof($choice) == 1) {
347 /* a single choice */
348 foreach($this->mVariants
as $v)
349 $carray[$v] = $choice[0];
352 foreach($choice as $c) {
353 $v = explode($this->mMarkup
['codesep'], $c);
354 if(sizeof($v) != 2) // syntax error, skip
356 $carray[trim($v[0])] = trim($v[1]);
363 * if a language supports multiple variants, it is
364 * possible that non-existing link in one variant
365 * actually exists in another variant. this function
366 * tries to find it. See e.g. LanguageZh.php
368 * @param string $link the name of the link
369 * @param mixed $nt the title object of the link
370 * @return null the input parameters may be modified upon return
373 function findVariantLink( &$link, &$nt ) {
374 static $count=0; //used to limit this operation
375 static $cache=array();
376 global $wgDisableLangConversion;
377 $pref = $this->getPreferredVariant();
380 $ns = $nt->getNamespace();
381 if( $count > 50 && $ns != NS_CATEGORY
)
384 $variants = $this->autoConvertToAllVariants($link);
385 if($variants == false) //give up
387 foreach( $variants as $v ) {
388 if(isset($cache[$v]))
391 $varnt = Title
::newFromText( $v );
392 if( $varnt && $varnt->getArticleID() > 0 ) {
394 if( !$wgDisableLangConversion )
402 * returns language specific hash options
406 function getExtraHashOptions() {
407 $variant = $this->getPreferredVariant();
408 return '!' . $variant ;
412 * get title text as defined in the body of the article text
416 function getParsedTitle() {
417 return $this->mTitleDisplay
;
421 * a write lock to the cache
425 function lockCache() {
428 for($i=0; $i<30; $i++
) {
429 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
441 function unlockCache() {
443 $wgMemc->delete($this->mCacheKey
. "lock");
448 * Load default conversion tables
449 * This method must be implemented in derived class
453 function loadDefaultTables() {
454 $name = get_class($this);
455 wfDie("Must implement loadDefaultTables() method in class $name");
459 * load conversion tables either from the cache or the disk
462 function loadTables($fromcache=true) {
464 if( $this->mTablesLoaded
)
466 $this->mTablesLoaded
= true;
468 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
469 if( !empty( $this->mTables
) ) //all done
472 // not in cache, or we need a fresh reload.
473 // we will first load the default tables
474 // then update them using things in MediaWiki:Zhconversiontable/*
475 global $wgMessageCache;
476 $this->loadDefaultTables();
477 foreach($this->mVariants
as $var) {
478 $cached = $this->parseCachedTable($var);
479 $this->mTables
[$var] = array_merge($this->mTables
[$var], $cached);
482 $this->postLoadTables();
484 if($this->lockCache()) {
485 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
486 $this->unlockCache();
491 * Hook for post processig after conversion tables are loaded
494 function postLoadTables() {}
497 * Reload the conversion tables
501 function reloadTables() {
503 unset($this->mTables
);
504 $this->mTablesLoaded
= false;
505 $this->loadTables(false);
510 * parse the conversion table stored in the cache
512 * the tables should be in blocks of the following form:
520 * to make the tables more manageable, subpages are allowed
521 * and will be parsed recursively if $recursive=true
525 function parseCachedTable($code, $subpage='', $recursive=true) {
526 global $wgMessageCache;
527 static $parsed = array();
529 if(!is_object($wgMessageCache))
532 $key = 'Conversiontable/'.$code;
534 $key .= '/' . $subpage;
536 if(array_key_exists($key, $parsed))
540 $txt = $wgMessageCache->get( $key, true, true, true );
542 // get all subpage links of the form
543 // [[MediaWiki:conversiontable/zh-xx/...|...]]
544 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
545 $subs = explode('[[', $txt);
547 foreach( $subs as $sub ) {
548 $link = explode(']]', $sub, 2);
549 if(count($link) != 2)
551 $b = explode('|', $link[0]);
552 $b = explode('/', trim($b[0]), 3);
558 if($b[0] == $linkhead && $b[1] == $code) {
559 $sublinks[] = $sublink;
564 // parse the mappings in this page
565 $blocks = explode($this->mMarkup
['begin'], $txt);
566 array_shift($blocks);
568 foreach($blocks as $block) {
569 $mappings = explode($this->mMarkup
['end'], $block, 2);
570 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
571 $table = explode( ';', $stripped );
572 foreach( $table as $t ) {
573 $m = explode( '=>', $t );
574 if( count( $m ) != 2)
576 // trim any trailling comments starting with '//'
577 $tt = explode('//', $m[1], 2);
578 $ret[trim($m[0])] = trim($tt[0]);
581 $parsed[$key] = true;
584 // recursively parse the subpages
586 foreach($sublinks as $link) {
587 $s = $this->parseCachedTable($code, $link, $recursive);
588 $ret = array_merge($ret, $s);
592 if ($this->mUcfirst
) {
593 foreach ($ret as $k => $v) {
594 $ret[LanguageUtf8
::ucfirst($k)] = LanguageUtf8
::ucfirst($v);
601 * Enclose a string with the "no conversion" tag. This is used by
602 * various functions in the Parser
604 * @param string $text text to be tagged for no conversion
605 * @return string the tagged text
607 function markNoConversion($text) {
608 # don't mark if already marked
609 if(strpos($text, $this->mMarkup
['begin']) ||
610 strpos($text, $this->mMarkup
['end']))
613 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
618 * convert the sorting key for category links. this should make different
619 * keys that are variants of each other map to the same key
621 function convertCategoryKey( $key ) {
625 * hook to refresh the cache of conversion tables when
626 * MediaWiki:conversiontable* is updated
629 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
630 $titleobj = $article->getTitle();
631 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
633 global $wgContLang; // should be an LanguageZh.
634 if(get_class($wgContLang) != 'languagezh')
637 $title = $titleobj->getDBkey();
638 $t = explode('/', $title, 3);
640 if( $c > 1 && $t[0] == 'Conversiontable' ) {
641 if(in_array($t[1], $this->mVariants
)) {
642 $this->reloadTables();