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 __construct($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]+';
149 // this one is needed when the text is inside an html markup
150 $htmlfix = '|<[^>]+=\"[^(>=)]*$|^[^(<>=\")]*\"[^>]*>';
152 $reg = '/<[^>]+>|&[a-z#][a-z0-9]+;' . $marker . $htmlfix . '/';
154 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
157 $m = array_shift($matches);
158 $ret = strtr($m[0], $this->mTables
[$toVariant]);
159 $mstart = $m[1]+
strlen($m[0]);
160 foreach($matches as $m) {
161 $ret .= substr($text, $mstart, $m[1]-$mstart);
162 $ret .= strtr($m[0], $this->mTables
[$toVariant]);
163 $mstart = $m[1] +
strlen($m[0]);
165 wfProfileOut( $fname );
170 * convert text to all supported variants
172 * @param string $text the text to be converted
173 * @return array of string
176 function autoConvertToAllVariants($text) {
177 $fname="LanguageConverter::autoConvertToAllVariants";
178 wfProfileIn( $fname );
179 if( !$this->mTablesLoaded
)
183 foreach($this->mVariants
as $variant) {
184 $ret[$variant] = strtr($text, $this->mTables
[$variant]);
186 wfProfileOut( $fname );
191 * Convert text using a parser object for context
193 function parserConvert( $text, &$parser ) {
194 global $wgDisableLangConversion;
195 /* don't do anything if this is the conversion table */
196 if ( $parser->mTitle
->getNamespace() == NS_MEDIAWIKI
&&
197 strpos($parser->mTitle
->getText
, "Conversiontable") !== false )
202 if($wgDisableLangConversion)
205 $text = $this->convert( $text );
206 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
211 * convert text to different variants of a language. the automatic
212 * conversion is done in autoConvert(). here we parse the text
213 * marked with -{}-, which specifies special conversions of the
214 * text that can not be accomplished in autoConvert()
216 * syntax of the markup:
217 * -{code1:text1;code2:text2;...}- or
218 * -{text}- in which case no conversion should take place for text
220 * @param string $text text to be converted
221 * @param bool $isTitle whether this conversion is for the article title
222 * @return string converted text
225 function convert( $text , $isTitle=false) {
226 $mw =& MagicWord
::get( MAG_NOTITLECONVERT
);
227 if( $mw->matchAndRemove( $text ) )
228 $this->mDoTitleConvert
= false;
230 $mw =& MagicWord
::get( MAG_NOCONTENTCONVERT
);
231 if( $mw->matchAndRemove( $text ) ) {
232 $this->mDoContentConvert
= false;
235 // no conversion if redirecting
236 $mw =& MagicWord
::get( MAG_REDIRECT
);
237 if( $mw->matchStart( $text ))
241 if( !$this->mDoTitleConvert
) {
242 $this->mTitleDisplay
= $text;
245 if( !empty($this->mTitleDisplay
))
246 return $this->mTitleDisplay
;
249 $isredir = $wgRequest->getText( 'redirect', 'yes' );
250 $action = $wgRequest->getText( 'action' );
251 if ( $isredir == 'no' ||
$action == 'edit' ) {
255 $this->mTitleDisplay
= $this->autoConvert($text);
256 return $this->mTitleDisplay
;
260 if( !$this->mDoContentConvert
)
263 $plang = $this->getPreferredVariant();
264 if( isset( $this->mVariantFallbacks
[$plang] ) ) {
265 $fallback = $this->mVariantFallbacks
[$plang];
267 // This sounds... bad?
271 $tarray = explode($this->mMarkup
['begin'], $text);
272 $tfirst = array_shift($tarray);
273 $text = $this->autoConvert($tfirst);
274 foreach($tarray as $txt) {
275 $marked = explode($this->mMarkup
['end'], $txt, 2);
277 $tt = explode($this->mMarkup
['flagsep'], $marked[0], 2);
279 if(sizeof($tt) == 2) {
280 $f = explode($this->mMarkup
['varsep'], $tt[0]);
283 if(array_key_exists($ff, $this->mFlags
) &&
284 !array_key_exists($this->mFlags
[$ff], $flags))
285 $flags[] = $this->mFlags
[$ff];
292 #FIXME: may cause trouble here...
293 //strip since it interferes with the parsing, plus,
294 //all spaces should be stripped in this tag anyway.
295 $rules = str_replace(' ', '', $rules);
297 $carray = $this->parseManualRule($rules, $flags);
299 if(array_key_exists($plang, $carray))
300 $disp = $carray[$plang];
301 else if(array_key_exists($fallback, $carray))
302 $disp = $carray[$fallback];
304 if(in_array('T', $flags))
305 $this->mTitleDisplay
= $disp;
309 if(in_array('A', $flags)) {
310 /* modify the conversion table for this session*/
312 /* fill in the missing variants, if any,
314 foreach($this->mVariants
as $v) {
315 if(!array_key_exists($v, $carray)) {
316 $vf = $this->getVariantFallback($v);
317 if(array_key_exists($vf, $carray))
318 $carray[$v] = $carray[$vf];
322 foreach($this->mVariants
as $vfrom) {
323 if(!array_key_exists($vfrom, $carray))
325 foreach($this->mVariants
as $vto) {
328 if(!array_key_exists($vto, $carray))
330 $this->mTables
[$vto][$carray[$vfrom]] = $carray[$vto];
339 if(array_key_exists(1, $marked))
340 $text .= $this->autoConvert($marked[1]);
347 * parse the manually marked conversion rule
348 * @param string $rule the text of the rule
349 * @return array of the translation in each variant
352 function parseManualRule($rules, $flags=array()) {
354 $choice = explode($this->mMarkup
['varsep'], $rules);
356 if(sizeof($choice) == 1) {
357 /* a single choice */
358 foreach($this->mVariants
as $v)
359 $carray[$v] = $choice[0];
362 foreach($choice as $c) {
363 $v = explode($this->mMarkup
['codesep'], $c);
364 if(sizeof($v) != 2) // syntax error, skip
366 $carray[trim($v[0])] = trim($v[1]);
373 * if a language supports multiple variants, it is
374 * possible that non-existing link in one variant
375 * actually exists in another variant. this function
376 * tries to find it. See e.g. LanguageZh.php
378 * @param string $link the name of the link
379 * @param mixed $nt the title object of the link
380 * @return null the input parameters may be modified upon return
383 function findVariantLink( &$link, &$nt ) {
384 static $count=0; //used to limit this operation
385 static $cache=array();
386 global $wgDisableLangConversion;
387 $pref = $this->getPreferredVariant();
390 $ns = $nt->getNamespace();
391 if( $count > 50 && $ns != NS_CATEGORY
)
394 $variants = $this->autoConvertToAllVariants($link);
395 if($variants == false) //give up
397 foreach( $variants as $v ) {
398 if(isset($cache[$v]))
401 $varnt = Title
::newFromText( $v, $ns );
402 if( $varnt && $varnt->getArticleID() > 0 ) {
404 if( !$wgDisableLangConversion )
412 * returns language specific hash options
416 function getExtraHashOptions() {
417 $variant = $this->getPreferredVariant();
418 return '!' . $variant ;
422 * get title text as defined in the body of the article text
426 function getParsedTitle() {
427 return $this->mTitleDisplay
;
431 * a write lock to the cache
435 function lockCache() {
438 for($i=0; $i<30; $i++
) {
439 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
451 function unlockCache() {
453 $wgMemc->delete($this->mCacheKey
. "lock");
458 * Load default conversion tables
459 * This method must be implemented in derived class
463 function loadDefaultTables() {
464 $name = get_class($this);
465 wfDie("Must implement loadDefaultTables() method in class $name");
469 * load conversion tables either from the cache or the disk
472 function loadTables($fromcache=true) {
474 if( $this->mTablesLoaded
)
476 $this->mTablesLoaded
= true;
478 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
479 if( !empty( $this->mTables
) ) //all done
482 // not in cache, or we need a fresh reload.
483 // we will first load the default tables
484 // then update them using things in MediaWiki:Zhconversiontable/*
485 global $wgMessageCache;
486 $this->loadDefaultTables();
487 foreach($this->mVariants
as $var) {
488 $cached = $this->parseCachedTable($var);
489 $this->mTables
[$var] = array_merge($this->mTables
[$var], $cached);
492 $this->postLoadTables();
494 if($this->lockCache()) {
495 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
496 $this->unlockCache();
501 * Hook for post processig after conversion tables are loaded
504 function postLoadTables() {}
507 * Reload the conversion tables
511 function reloadTables() {
513 unset($this->mTables
);
514 $this->mTablesLoaded
= false;
515 $this->loadTables(false);
520 * parse the conversion table stored in the cache
522 * the tables should be in blocks of the following form:
530 * to make the tables more manageable, subpages are allowed
531 * and will be parsed recursively if $recursive=true
535 function parseCachedTable($code, $subpage='', $recursive=true) {
536 global $wgMessageCache;
537 static $parsed = array();
539 if(!is_object($wgMessageCache))
542 $key = 'Conversiontable/'.$code;
544 $key .= '/' . $subpage;
546 if(array_key_exists($key, $parsed))
550 $txt = $wgMessageCache->get( $key, true, true, true );
552 // get all subpage links of the form
553 // [[MediaWiki:conversiontable/zh-xx/...|...]]
554 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
555 $subs = explode('[[', $txt);
557 foreach( $subs as $sub ) {
558 $link = explode(']]', $sub, 2);
559 if(count($link) != 2)
561 $b = explode('|', $link[0]);
562 $b = explode('/', trim($b[0]), 3);
568 if($b[0] == $linkhead && $b[1] == $code) {
569 $sublinks[] = $sublink;
574 // parse the mappings in this page
575 $blocks = explode($this->mMarkup
['begin'], $txt);
576 array_shift($blocks);
578 foreach($blocks as $block) {
579 $mappings = explode($this->mMarkup
['end'], $block, 2);
580 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
581 $table = explode( ';', $stripped );
582 foreach( $table as $t ) {
583 $m = explode( '=>', $t );
584 if( count( $m ) != 2)
586 // trim any trailling comments starting with '//'
587 $tt = explode('//', $m[1], 2);
588 $ret[trim($m[0])] = trim($tt[0]);
591 $parsed[$key] = true;
594 // recursively parse the subpages
596 foreach($sublinks as $link) {
597 $s = $this->parseCachedTable($code, $link, $recursive);
598 $ret = array_merge($ret, $s);
602 if ($this->mUcfirst
) {
603 foreach ($ret as $k => $v) {
604 $ret[LanguageUtf8
::ucfirst($k)] = LanguageUtf8
::ucfirst($v);
611 * Enclose a string with the "no conversion" tag. This is used by
612 * various functions in the Parser
614 * @param string $text text to be tagged for no conversion
615 * @return string the tagged text
617 function markNoConversion($text) {
618 # don't mark if already marked
619 if(strpos($text, $this->mMarkup
['begin']) ||
620 strpos($text, $this->mMarkup
['end']))
623 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
628 * convert the sorting key for category links. this should make different
629 * keys that are variants of each other map to the same key
631 function convertCategoryKey( $key ) {
635 * hook to refresh the cache of conversion tables when
636 * MediaWiki:conversiontable* is updated
639 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
640 $titleobj = $article->getTitle();
641 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
643 global $wgContLang; // should be an LanguageZh.
644 if(get_class($wgContLang) != 'languagezh')
647 $title = $titleobj->getDBkey();
648 $t = explode('/', $title, 3);
650 if( $c > 1 && $t[0] == 'Conversiontable' ) {
651 if(in_array($t[1], $this->mVariants
)) {
652 $this->reloadTables();