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 * @param boolean $fromUser Get it from $wgUser's preferences
77 * @return string the preferred language code
80 function getPreferredVariant( $fromUser = true ) {
81 global $wgUser, $wgRequest;
83 if($this->mPreferredVariant
)
84 return $this->mPreferredVariant
;
86 // see if the preference is set in the request
87 $req = $wgRequest->getText( 'variant' );
88 if( in_array( $req, $this->mVariants
) ) {
89 $this->mPreferredVariant
= $req;
93 // get language variant preference from logged in users
94 // Don't call this on stub objects because that causes infinite
95 // recursion during initialisation
96 if( $fromUser && $wgUser->isLoggedIn() ) {
97 $this->mPreferredVariant
= $wgUser->getOption('variant');
98 return $this->mPreferredVariant
;
101 # FIXME rewrite code for parsing http header. The current code
102 # is written specific for detecting zh- variants
103 if( !$this->mPreferredVariant
) {
104 // see if some supported language variant is set in the
105 // http header, but we don't set the mPreferredVariant
106 // variable in case this is called before the user's
107 // preference is loaded
108 $pv=$this->mMainLanguageCode
;
109 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
110 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
111 $zh = strstr($header, 'zh-');
113 $pv = substr($zh,0,5);
121 * dictionary-based conversion
123 * @param string $text the text to be converted
124 * @param string $toVariant the target language code
125 * @return string the converted text
128 function autoConvert($text, $toVariant=false) {
129 $fname="LanguageConverter::autoConvert";
131 wfProfileIn( $fname );
133 if(!$this->mTablesLoaded
)
137 $toVariant = $this->getPreferredVariant();
138 if(!in_array($toVariant, $this->mVariants
))
141 /* we convert everything except:
142 1. html markups (anything between < and >)
144 3. place holders created by the parser
147 if (isset($wgParser))
148 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
152 // this one is needed when the text is inside an html markup
153 $htmlfix = '|<[^>]+=\"[^(>=)]*$|^[^(<>=\")]*\"[^>]*>';
155 $reg = '/<[^>]+>|&[a-z#][a-z0-9]+;' . $marker . $htmlfix . '/';
157 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
160 $m = array_shift($matches);
161 $ret = strtr($m[0], $this->mTables
[$toVariant]);
162 $mstart = $m[1]+
strlen($m[0]);
163 foreach($matches as $m) {
164 $ret .= substr($text, $mstart, $m[1]-$mstart);
165 $ret .= strtr($m[0], $this->mTables
[$toVariant]);
166 $mstart = $m[1] +
strlen($m[0]);
168 wfProfileOut( $fname );
173 * convert text to all supported variants
175 * @param string $text the text to be converted
176 * @return array of string
179 function autoConvertToAllVariants($text) {
180 $fname="LanguageConverter::autoConvertToAllVariants";
181 wfProfileIn( $fname );
182 if( !$this->mTablesLoaded
)
186 foreach($this->mVariants
as $variant) {
187 $ret[$variant] = strtr($text, $this->mTables
[$variant]);
189 wfProfileOut( $fname );
194 * Convert text using a parser object for context
196 function parserConvert( $text, &$parser ) {
197 global $wgDisableLangConversion;
198 /* don't do anything if this is the conversion table */
199 if ( $parser->mTitle
->getNamespace() == NS_MEDIAWIKI
&&
200 strpos($parser->mTitle
->getText
, "Conversiontable") !== false )
205 if($wgDisableLangConversion)
208 $text = $this->convert( $text );
209 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
214 * convert text to different variants of a language. the automatic
215 * conversion is done in autoConvert(). here we parse the text
216 * marked with -{}-, which specifies special conversions of the
217 * text that can not be accomplished in autoConvert()
219 * syntax of the markup:
220 * -{code1:text1;code2:text2;...}- or
221 * -{text}- in which case no conversion should take place for text
223 * @param string $text text to be converted
224 * @param bool $isTitle whether this conversion is for the article title
225 * @return string converted text
228 function convert( $text , $isTitle=false) {
229 $mw =& MagicWord
::get( 'notitleconvert' );
230 if( $mw->matchAndRemove( $text ) )
231 $this->mDoTitleConvert
= false;
233 $mw =& MagicWord
::get( 'nocontentconvert' );
234 if( $mw->matchAndRemove( $text ) ) {
235 $this->mDoContentConvert
= false;
238 // no conversion if redirecting
239 $mw =& MagicWord
::get( 'redirect' );
240 if( $mw->matchStart( $text ))
244 if( !$this->mDoTitleConvert
) {
245 $this->mTitleDisplay
= $text;
248 if( !empty($this->mTitleDisplay
))
249 return $this->mTitleDisplay
;
252 $isredir = $wgRequest->getText( 'redirect', 'yes' );
253 $action = $wgRequest->getText( 'action' );
254 if ( $isredir == 'no' ||
$action == 'edit' ) {
258 $this->mTitleDisplay
= $this->autoConvert($text);
259 return $this->mTitleDisplay
;
263 if( !$this->mDoContentConvert
)
266 $plang = $this->getPreferredVariant();
267 if( isset( $this->mVariantFallbacks
[$plang] ) ) {
268 $fallback = $this->mVariantFallbacks
[$plang];
270 // This sounds... bad?
274 $tarray = explode($this->mMarkup
['begin'], $text);
275 $tfirst = array_shift($tarray);
276 $text = $this->autoConvert($tfirst);
277 foreach($tarray as $txt) {
278 $marked = explode($this->mMarkup
['end'], $txt, 2);
280 $tt = explode($this->mMarkup
['flagsep'], $marked[0], 2);
282 if(sizeof($tt) == 2) {
283 $f = explode($this->mMarkup
['varsep'], $tt[0]);
286 if(array_key_exists($ff, $this->mFlags
) &&
287 !array_key_exists($this->mFlags
[$ff], $flags))
288 $flags[] = $this->mFlags
[$ff];
295 #FIXME: may cause trouble here...
296 //strip since it interferes with the parsing, plus,
297 //all spaces should be stripped in this tag anyway.
298 $rules = str_replace(' ', '', $rules);
300 $carray = $this->parseManualRule($rules, $flags);
302 if(array_key_exists($plang, $carray))
303 $disp = $carray[$plang];
304 else if(array_key_exists($fallback, $carray))
305 $disp = $carray[$fallback];
307 if(in_array('T', $flags))
308 $this->mTitleDisplay
= $disp;
312 if(in_array('A', $flags)) {
313 /* modify the conversion table for this session*/
315 /* fill in the missing variants, if any,
317 foreach($this->mVariants
as $v) {
318 if(!array_key_exists($v, $carray)) {
319 $vf = $this->getVariantFallback($v);
320 if(array_key_exists($vf, $carray))
321 $carray[$v] = $carray[$vf];
325 foreach($this->mVariants
as $vfrom) {
326 if(!array_key_exists($vfrom, $carray))
328 foreach($this->mVariants
as $vto) {
331 if(!array_key_exists($vto, $carray))
333 $this->mTables
[$vto][$carray[$vfrom]] = $carray[$vto];
342 if(array_key_exists(1, $marked))
343 $text .= $this->autoConvert($marked[1]);
350 * parse the manually marked conversion rule
351 * @param string $rule the text of the rule
352 * @return array of the translation in each variant
355 function parseManualRule($rules, $flags=array()) {
357 $choice = explode($this->mMarkup
['varsep'], $rules);
359 if(sizeof($choice) == 1) {
360 /* a single choice */
361 foreach($this->mVariants
as $v)
362 $carray[$v] = $choice[0];
365 foreach($choice as $c) {
366 $v = explode($this->mMarkup
['codesep'], $c);
367 if(sizeof($v) != 2) // syntax error, skip
369 $carray[trim($v[0])] = trim($v[1]);
376 * if a language supports multiple variants, it is
377 * possible that non-existing link in one variant
378 * actually exists in another variant. this function
379 * tries to find it. See e.g. LanguageZh.php
381 * @param string $link the name of the link
382 * @param mixed $nt the title object of the link
383 * @return null the input parameters may be modified upon return
386 function findVariantLink( &$link, &$nt ) {
387 static $count=0; //used to limit this operation
388 static $cache=array();
389 global $wgDisableLangConversion;
390 $pref = $this->getPreferredVariant();
393 $ns = $nt->getNamespace();
394 if( $count > 50 && $ns != NS_CATEGORY
)
397 $variants = $this->autoConvertToAllVariants($link);
398 if($variants == false) //give up
400 foreach( $variants as $v ) {
401 if(isset($cache[$v]))
404 $varnt = Title
::newFromText( $v, $ns );
405 if( $varnt && $varnt->getArticleID() > 0 ) {
407 if( !$wgDisableLangConversion )
415 * returns language specific hash options
419 function getExtraHashOptions() {
420 $variant = $this->getPreferredVariant();
421 return '!' . $variant ;
425 * get title text as defined in the body of the article text
429 function getParsedTitle() {
430 return $this->mTitleDisplay
;
434 * a write lock to the cache
438 function lockCache() {
441 for($i=0; $i<30; $i++
) {
442 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
454 function unlockCache() {
456 $wgMemc->delete($this->mCacheKey
. "lock");
461 * Load default conversion tables
462 * This method must be implemented in derived class
466 function loadDefaultTables() {
467 $name = get_class($this);
468 wfDie("Must implement loadDefaultTables() method in class $name");
472 * load conversion tables either from the cache or the disk
475 function loadTables($fromcache=true) {
477 if( $this->mTablesLoaded
)
479 $this->mTablesLoaded
= true;
481 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
482 if( !empty( $this->mTables
) ) //all done
485 // not in cache, or we need a fresh reload.
486 // we will first load the default tables
487 // then update them using things in MediaWiki:Zhconversiontable/*
488 global $wgMessageCache;
489 $this->loadDefaultTables();
490 foreach($this->mVariants
as $var) {
491 $cached = $this->parseCachedTable($var);
492 $this->mTables
[$var] = array_merge($this->mTables
[$var], $cached);
495 $this->postLoadTables();
497 if($this->lockCache()) {
498 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
499 $this->unlockCache();
504 * Hook for post processig after conversion tables are loaded
507 function postLoadTables() {}
510 * Reload the conversion tables
514 function reloadTables() {
516 unset($this->mTables
);
517 $this->mTablesLoaded
= false;
518 $this->loadTables(false);
523 * parse the conversion table stored in the cache
525 * the tables should be in blocks of the following form:
533 * to make the tables more manageable, subpages are allowed
534 * and will be parsed recursively if $recursive=true
538 function parseCachedTable($code, $subpage='', $recursive=true) {
539 global $wgMessageCache;
540 static $parsed = array();
542 if(!is_object($wgMessageCache))
545 $key = 'Conversiontable/'.$code;
547 $key .= '/' . $subpage;
549 if(array_key_exists($key, $parsed))
553 $txt = $wgMessageCache->get( $key, true, true, true );
555 // get all subpage links of the form
556 // [[MediaWiki:conversiontable/zh-xx/...|...]]
557 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
558 $subs = explode('[[', $txt);
560 foreach( $subs as $sub ) {
561 $link = explode(']]', $sub, 2);
562 if(count($link) != 2)
564 $b = explode('|', $link[0]);
565 $b = explode('/', trim($b[0]), 3);
571 if($b[0] == $linkhead && $b[1] == $code) {
572 $sublinks[] = $sublink;
577 // parse the mappings in this page
578 $blocks = explode($this->mMarkup
['begin'], $txt);
579 array_shift($blocks);
581 foreach($blocks as $block) {
582 $mappings = explode($this->mMarkup
['end'], $block, 2);
583 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
584 $table = explode( ';', $stripped );
585 foreach( $table as $t ) {
586 $m = explode( '=>', $t );
587 if( count( $m ) != 2)
589 // trim any trailling comments starting with '//'
590 $tt = explode('//', $m[1], 2);
591 $ret[trim($m[0])] = trim($tt[0]);
594 $parsed[$key] = true;
597 // recursively parse the subpages
599 foreach($sublinks as $link) {
600 $s = $this->parseCachedTable($code, $link, $recursive);
601 $ret = array_merge($ret, $s);
605 if ($this->mUcfirst
) {
606 foreach ($ret as $k => $v) {
607 $ret[LanguageUtf8
::ucfirst($k)] = LanguageUtf8
::ucfirst($v);
614 * Enclose a string with the "no conversion" tag. This is used by
615 * various functions in the Parser
617 * @param string $text text to be tagged for no conversion
618 * @return string the tagged text
620 function markNoConversion($text) {
621 # don't mark if already marked
622 if(strpos($text, $this->mMarkup
['begin']) ||
623 strpos($text, $this->mMarkup
['end']))
626 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
631 * convert the sorting key for category links. this should make different
632 * keys that are variants of each other map to the same key
634 function convertCategoryKey( $key ) {
638 * hook to refresh the cache of conversion tables when
639 * MediaWiki:conversiontable* is updated
642 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
643 $titleobj = $article->getTitle();
644 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
646 global $wgContLang; // should be an LanguageZh.
647 if(get_class($wgContLang) != 'languagezh')
650 $title = $titleobj->getDBkey();
651 $t = explode('/', $title, 3);
653 if( $c > 1 && $t[0] == 'Conversiontable' ) {
654 if(in_array($t[1], $this->mVariants
)) {
655 $this->reloadTables();