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;
24 * @param string $maincode the main language code of this language
25 * @param array $variants the supported variants of this language
26 * @param array $variantfallback the fallback language of each variant
27 * @param array $markup array defining the markup used for manual conversion
30 function LanguageConverter($langobj, $maincode,
32 $variantfallbacks=array(),
33 $markup=array('begin'=>'-{',
38 $this->mLangObj
= $langobj;
39 $this->mMainLanguageCode
= $maincode;
40 $this->mVariants
= $variants;
41 $this->mVariantFallbacks
= $variantfallbacks;
42 $this->mCacheKey
= $wgDBname . ":conversiontables";
43 $this->mMarkup
= $markup;
49 function getVariants() {
50 return $this->mVariants
;
54 * in case some variant is not defined in the markup, we need
55 * to have some fallback. for example, in zh, normally people
56 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
57 * when zh-sg is preferred but not defined, we will pick zh-cn
58 * in this case. right now this is only used by zh.
60 * @param string $v the language code of the variant
61 * @return string the code of the fallback language or false if there is no fallback
64 function getVariantFallback($v) {
65 return $this->mVariantFallbacks
[$v];
70 * get preferred language variants.
71 * @return string the preferred language code
74 function getPreferredVariant() {
75 global $wgUser, $wgRequest;
77 if($this->mPreferredVariant
)
78 return $this->mPreferredVariant
;
80 // see if the preference is set in the request
81 $req = $wgRequest->getText( 'variant' );
82 if( in_array( $req, $this->mVariants
) ) {
83 $this->mPreferredVariant
= $req;
87 // get language variant preference from logged in users
88 if(is_object($wgUser) && $wgUser->isLoggedIn() ) {
89 $this->mPreferredVariant
= $wgUser->getOption('variant');
92 # FIXME rewrite code for parsing http header. The current code
93 # is written specific for detecting zh- variants
94 if( !$this->mPreferredVariant
) {
95 // see if some zh- variant is set in the http header,
96 $this->mPreferredVariant
=$this->mMainLanguageCode
;
97 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
98 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
99 $zh = strstr($header, 'zh-');
101 $this->mPreferredVariant
= substr($zh,0,5);
106 return $this->mPreferredVariant
;
110 * dictionary-based conversion
112 * @param string $text the text to be converted
113 * @param string $toVariant the target language code
114 * @return string the converted text
117 function autoConvert($text, $toVariant=false) {
118 $fname="LanguageConverter::autoConvert";
119 wfProfileIn( $fname );
121 if(!$this->mTablesLoaded
)
125 $toVariant = $this->getPreferredVariant();
126 if(!in_array($toVariant, $this->mVariants
))
131 $a = explode('<', $text);
132 $a0 = array_shift($a);
133 $ret .= strtr($a0, $this->mTables
[$toVariant]);
134 foreach( $a as $aa ) {
135 $b = explode('>', $aa, 2);
138 $ret .= '>' . strtr($b[1], $this->mTables
[$toVariant]);
141 # /* put back the marker if any */
143 # $reg = '<'.$reg.'>';
144 # $ret = preg_replace('/'.$reg.'/', '${1}', $ret);
147 wfProfileOut( $fname );
152 * convert text to all supported variants
154 * @param string $text the text to be converted
155 * @return array of string
158 function autoConvertToAllVariants($text) {
159 $fname="LanguageConverter::autoConvertToAllVariants";
160 wfProfileIn( $fname );
161 if( !$this->mTablesLoaded
)
165 foreach($this->mVariants
as $variant) {
166 $ret[$variant] = strtr($text, $this->mTables
[$variant]);
168 wfProfileOut( $fname );
173 * convert text to different variants of a language. the automatic
174 * conversion is done in autoConvert(). here we parse the text
175 * marked with -{}-, which specifies special conversions of the
176 * text that can not be accomplished in autoConvert()
178 * syntax of the markup:
179 * -{code1:text1;code2:text2;...}- or
180 * -{text}- in which case no conversion should take place for text
182 * @param string $text text to be converted
183 * @param bool $isTitle whether this conversion is for the article title
184 * @return string converted text
187 function convert( $text , $isTitle=false) {
188 global $wgDisableLangConversion;
189 if($wgDisableLangConversion)
192 $mw =& MagicWord
::get( MAG_NOTITLECONVERT
);
193 if( $mw->matchAndRemove( $text ) )
194 $this->mDoTitleConvert
= false;
196 $mw =& MagicWord
::get( MAG_NOCONTENTCONVERT
);
197 if( $mw->matchAndRemove( $text ) ) {
198 $this->mDoContentConvert
= false;
201 // no conversion if redirecting
202 $mw =& MagicWord
::get( MAG_REDIRECT
);
203 if( $mw->matchStart( $text ))
207 if( !$this->mDoTitleConvert
) {
208 $this->mTitleDisplay
= $text;
211 if( !empty($this->mTitleDisplay
))
212 return $this->mTitleDisplay
;
215 $isredir = $wgRequest->getText( 'redirect', 'yes' );
216 $action = $wgRequest->getText( 'action' );
217 if ( $isredir == 'no' ||
$action == 'edit' ) {
221 $this->mTitleDisplay
= $this->autoConvert($text);
222 return $this->mTitleDisplay
;
226 if( !$this->mDoContentConvert
)
229 $search = array('/('.UNIQ_PREFIX
.'-[a-zA-Z0-9]+)/', //nowiki marker
230 '/(&[a-z#][a-z0-9]+;)/', //html entities
232 $replace = $this->mMarkup
['begin'].'${1}'.$this->mMarkup
['end'];
234 $text = preg_replace($search, $replace, $text);
236 $plang = $this->getPreferredVariant();
237 $fallback = $this->mVariantFallbacks
[$plang];
238 $tarray = explode($this->mMarkup
['begin'], $text);
239 $tfirst = array_shift($tarray);
240 $text = $this->autoConvert($tfirst);
241 foreach($tarray as $txt) {
242 $marked = explode($this->mMarkup
['end'], $txt);
244 //strip since it interferes with the parsing, plus,
245 //all spaces should be stripped in this tag anyway.
246 $marked[0] = str_replace(' ', '', $marked[0]);
248 /* see if this conversion has special meaning
250 -{T|zh-cn:foo;zh-tw:bar}-
251 # convert all occurence of foo/bar in this article:
252 -{A|zh-cn:foo;zh-tw:bar}-
256 $tt = explode("|", $marked[0], 2);
257 if(sizeof($tt) == 2) {
258 $flag = trim($tt[0]);
259 $choice = explode(";", $tt[1]);
263 $choice = explode($this->mMarkup
['varsep'], $marked[0]);
267 if(!array_key_exists(1, $choice)) {
268 /* a single choice */
271 /* fill the carray if the conversion is for the whole article*/
273 foreach($this->mVariants
as $v) {
279 foreach($choice as $c) {
280 $v = explode($this->mMarkup
['codesep'], $c);
281 if(sizeof($v) != 2) // syntax error, skip
283 $carray[trim($v[0])] = trim($v[1]);
285 if(array_key_exists($plang, $carray))
286 $disp = $carray[$plang];
287 else if(array_key_exists($fallback, $carray))
288 $disp = $carray[$fallback];
290 if(empty($disp)) { // syntax error
294 if($flag == 'T') // for title only
295 $this->mTitleDisplay
= $disp;
299 /* modify the conversion table for this session*/
301 /* fill in the missing variants, if any,
303 foreach($this->mVariants
as $v) {
304 if(!array_key_exists($v, $carray)) {
305 $vf = $this->getVariantFallback($v);
306 if(array_key_exists($vf, $carray))
307 $carray[$v] = $carray[$vf];
310 foreach($this->mVariants
as $vfrom) {
311 if(!array_key_exists($vfrom, $carray))
313 foreach($this->mVariants
as $vto) {
316 if(!array_key_exists($vto, $carray))
318 $this->mTables
[$vto][$carray[$vfrom]] = $carray[$vto];
324 if(array_key_exists(1, $marked))
325 $text .= $this->autoConvert($marked[1]);
333 * if a language supports multiple variants, it is
334 * possible that non-existing link in one variant
335 * actually exists in another variant. this function
336 * tries to find it. See e.g. LanguageZh.php
338 * @param string $link the name of the link
339 * @param mixed $nt the title object of the link
340 * @return null the input parameters may be modified upon return
343 function findVariantLink( &$link, &$nt ) {
344 static $count=0; //used to limit this operation
345 static $cache=array();
346 global $wgDisableLangConversion;
347 $pref = $this->getPreferredVariant();
351 $variants = $this->autoConvertToAllVariants($link);
352 if($variants == false) //give up
354 foreach( $variants as $v ) {
355 if(isset($cache[$v]))
358 $varnt = Title
::newFromText( $v );
359 if( $varnt && $varnt->getArticleID() > 0 ) {
361 if( !$wgDisableLangConversion && $pref != 'zh' )
369 * returns language specific hash options
373 function getExtraHashOptions() {
374 $variant = $this->getPreferredVariant();
375 return '!' . $variant ;
379 * get title text as defined in the body of the article text
383 function getParsedTitle() {
384 return $this->mTitleDisplay
;
388 * a write lock to the cache
392 function lockCache() {
395 for($i=0; $i<30; $i++
) {
396 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
408 function unlockCache() {
410 $wgMemc->delete($this->mCacheKey
. "lock");
415 * Load default conversion tables
416 * This method must be implemented in derived class
420 function loadDefaultTables() {
421 $name = get_class($this);
422 die("Must implement loadDefaultTables() method in class $name");
426 * load conversion tables either from the cache or the disk
429 function loadTables($fromcache=true) {
431 if( $this->mTablesLoaded
)
433 $this->mTablesLoaded
= true;
435 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
436 if( !empty( $this->mTables
) ) //all done
439 // not in cache, or we need a fresh reload.
440 // we will first load the default tables
441 // then update them using things in MediaWiki:Zhconversiontable/*
442 global $wgMessageCache;
443 $this->loadDefaultTables();
444 foreach($this->mVariants
as $var) {
445 $cached = $this->parseCachedTable($var);
446 $this->mTables
[$var] = array_merge($this->mTables
[$var], $cached);
449 $this->postLoadTables();
451 if($this->lockCache()) {
452 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
453 $this->unlockCache();
458 * Hook for post processig after conversion tables are loaded
461 function postLoadTables() {}
464 function updateTablexxxx($code, $table) {
466 if(!$this->mTablesLoaded
)
469 $this->mTables
[$code] = array_merge($this->mTables
[$code], $table);
470 if($this->lockCache()) {
471 $wgMemc->delete($this->mCacheKey
);
472 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
473 $this->unlockCache();
478 * Reload the conversion tables
482 function reloadTables() {
484 unset($this->mTables
);
485 $this->mTablesLoaded
= false;
486 $this->loadTables(false);
491 * parse the conversion table stored in the cache
493 * the tables should be in blocks of the following form:
501 * to make the tables more manageable, subpages are allowed
502 * and will be parsed recursively if $recursive=true
506 function parseCachedTable($code, $subpage='', $recursive=true) {
507 global $wgMessageCache;
508 static $parsed = array();
510 if(!is_object($wgMessageCache))
513 $key = 'Conversiontable/'.$code;
515 $key .= '/' . $subpage;
517 if(array_key_exists($key, $parsed))
521 $txt = $wgMessageCache->get( $key, true, true, true );
523 // get all subpage links of the form
524 // [[MediaWiki:conversiontable/zh-xx/...|...]]
525 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
526 $subs = explode('[[', $txt);
528 foreach( $subs as $sub ) {
529 $link = explode(']]', $sub, 2);
530 if(count($link) != 2)
532 $b = explode('|', $link[0]);
533 $b = explode('/', trim($b[0]), 3);
539 if($b[0] == $linkhead && $b[1] == $code) {
540 $sublinks[] = $sublink;
545 // parse the mappings in this page
546 $blocks = explode('-{', $txt);
547 array_shift($blocks);
549 foreach($blocks as $block) {
550 $mappings = explode('}-', $block, 2);
551 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
552 $table = explode( ';', $stripped );
553 foreach( $table as $t ) {
554 $m = explode( '=>', $t );
555 if( count( $m ) != 2)
557 // trim any trailling comments starting with '//'
558 $tt = explode('//', $m[1], 2);
559 $ret[trim($m[0])] = trim($tt[0]);
562 $parsed[$key] = true;
565 // recursively parse the subpages
567 foreach($sublinks as $link) {
568 $s = $this->parseCachedTable($code, $link, $recursive);
569 $ret = array_merge($ret, $s);
576 * Enclose a string with the "no conversion" tag. This is used by
577 * various functions in the Parser
579 * @param string $text text to be tagged for no conversion
580 * @return string the tagged text
582 function markNoConversion($text) {
583 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
587 * hook to refresh the cache of conversion tables when
588 * MediaWiki:conversiontable* is updated
591 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
592 $titleobj = $article->getTitle();
593 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
595 global $wgContLang; // should be an LanguageZh.
596 if(get_class($wgContLang) != 'languagezh')
599 $title = $titleobj->getDBkey();
600 $t = explode('/', $title, 3);
602 if( $c > 1 && $t[0] == 'Conversiontable' ) {
603 if(in_array($t[1], $this->mVariants
)) {
604 $this->reloadTables();