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;
18 var $mTitleDisplay='';
19 var $mDoTitleConvert=true, $mDoContentConvert=true;
24 var $mUcfirst = false;
25 var $mNoTitleConvert = false;
29 * @param string $maincode the main language code of this language
30 * @param array $variants the supported variants of this language
31 * @param array $variantfallback the fallback language of each variant
32 * @param array $markup array defining the markup used for manual conversion
33 * @param array $flags array defining the custom strings that maps to the flags
36 function __construct($langobj, $maincode,
38 $variantfallbacks=array(),
42 global $wgLegalTitleChars;
43 $this->mLangObj
= $langobj;
44 $this->mMainLanguageCode
= $maincode;
45 $this->mVariants
= $variants;
46 $this->mVariantFallbacks
= $variantfallbacks;
47 $this->mCacheKey
= $wgDBname . ":conversiontables";
48 $m = array('begin'=>'-{', 'flagsep'=>'|', 'codesep'=>':',
49 'varsep'=>';', 'end'=>'}-');
50 $this->mMarkup
= array_merge($m, $markup);
51 $f = array('A'=>'A', 'T'=>'T');
52 $this->mFlags
= array_merge($f, $flags);
53 if ( function_exists( 'fss_prep_replace' ) ) {
54 $this->mUseFss
= true;
61 function getVariants() {
62 return $this->mVariants
;
66 * in case some variant is not defined in the markup, we need
67 * to have some fallback. for example, in zh, normally people
68 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
69 * when zh-sg is preferred but not defined, we will pick zh-cn
70 * in this case. right now this is only used by zh.
72 * @param string $v the language code of the variant
73 * @return string the code of the fallback language or false if there is no fallback
76 function getVariantFallback($v) {
77 return $this->mVariantFallbacks
[$v];
82 * get preferred language variants.
83 * @param boolean $fromUser Get it from $wgUser's preferences
84 * @return string the preferred language code
87 function getPreferredVariant( $fromUser = true ) {
88 global $wgUser, $wgRequest;
90 if($this->mPreferredVariant
)
91 return $this->mPreferredVariant
;
93 // see if the preference is set in the request
94 $req = $wgRequest->getText( 'variant' );
95 if( in_array( $req, $this->mVariants
) ) {
96 $this->mPreferredVariant
= $req;
100 // get language variant preference from logged in users
101 // Don't call this on stub objects because that causes infinite
102 // recursion during initialisation
103 if( $fromUser && $wgUser->isLoggedIn() ) {
104 $this->mPreferredVariant
= $wgUser->getOption('variant');
105 return $this->mPreferredVariant
;
108 # FIXME rewrite code for parsing http header. The current code
109 # is written specific for detecting zh- variants
110 if( !$this->mPreferredVariant
) {
111 // see if some supported language variant is set in the
112 // http header, but we don't set the mPreferredVariant
113 // variable in case this is called before the user's
114 // preference is loaded
115 $pv=$this->mMainLanguageCode
;
116 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
117 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
118 $zh = strstr($header, 'zh-');
120 $pv = substr($zh,0,5);
128 * dictionary-based conversion
130 * @param string $text the text to be converted
131 * @param string $toVariant the target language code
132 * @return string the converted text
135 function autoConvert($text, $toVariant=false) {
136 $fname="LanguageConverter::autoConvert";
138 wfProfileIn( $fname );
140 if(!$this->mTablesLoaded
)
144 $toVariant = $this->getPreferredVariant();
145 if(!in_array($toVariant, $this->mVariants
))
148 /* we convert everything except:
149 1. html markups (anything between < and >)
151 3. place holders created by the parser
154 if (isset($wgParser))
155 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
159 // this one is needed when the text is inside an html markup
160 $htmlfix = '|<[^>]+$|^[^<>]*>';
162 // disable convert to variants between <code></code> tags
163 $codefix = '<code>.+?<\/code>|';
165 $reg = '/'.$codefix.'<[^>]+>|&[a-z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
167 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
169 $m = array_shift($matches);
171 $ret = $this->translate($m[0], $toVariant);
172 $mstart = $m[1]+
strlen($m[0]);
173 foreach($matches as $m) {
174 $ret .= substr($text, $mstart, $m[1]-$mstart);
175 $ret .= $this->translate($m[0], $toVariant);
176 $mstart = $m[1] +
strlen($m[0]);
178 wfProfileOut( $fname );
183 * Translate a string to a variant
184 * Doesn't process markup or do any of that other stuff, for that use convert()
186 * @param string $text Text to convert
187 * @param string $variant Variant language code
188 * @return string Translated text
190 function translate( $text, $variant ) {
191 if( !$this->mTablesLoaded
)
193 if ( $this->mUseFss
) {
194 return fss_exec_replace( $this->mFssObjects
[$variant], $text );
196 return strtr( $text, $this->mTables
[$variant] );
201 * convert text to all supported variants
203 * @param string $text the text to be converted
204 * @return array of string
207 function autoConvertToAllVariants($text) {
208 $fname="LanguageConverter::autoConvertToAllVariants";
209 wfProfileIn( $fname );
210 if( !$this->mTablesLoaded
)
214 foreach($this->mVariants
as $variant) {
215 $ret[$variant] = $this->translate($text, $variant);
218 wfProfileOut( $fname );
223 * convert link text to all supported variants
225 * @param string $text the text to be converted
226 * @return array of string
229 function convertLinkToAllVariants($text) {
230 if( !$this->mTablesLoaded
)
234 $tarray = explode($this->mMarkup
['begin'], $text);
235 $tfirst = array_shift($tarray);
237 foreach($this->mVariants
as $variant)
238 $ret[$variant] = $this->translate($tfirst,$variant);
240 foreach($tarray as $txt) {
241 $marked = explode($this->mMarkup
['end'], $txt, 2);
243 foreach($this->mVariants
as $variant){
244 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
245 if(array_key_exists(1, $marked))
246 $ret[$variant] .= $this->translate($marked[1],$variant);
256 * Convert text using a parser object for context
258 function parserConvert( $text, &$parser ) {
259 global $wgDisableLangConversion;
260 /* don't do anything if this is the conversion table */
261 if ( $parser->mTitle
->getNamespace() == NS_MEDIAWIKI
&&
262 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
267 if($wgDisableLangConversion)
270 $text = $this->convert( $text );
271 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
276 * convert text to different variants of a language. the automatic
277 * conversion is done in autoConvert(). here we parse the text
278 * marked with -{}-, which specifies special conversions of the
279 * text that can not be accomplished in autoConvert()
281 * syntax of the markup:
282 * -{code1:text1;code2:text2;...}- or
283 * -{text}- in which case no conversion should take place for text
285 * @param string $text text to be converted
286 * @param bool $isTitle whether this conversion is for the article title
287 * @return string converted text
290 function convert( $text , $isTitle=false) {
291 $mw =& MagicWord
::get( 'notitleconvert' );
292 if( $mw->matchAndRemove( $text ) )
293 $this->mDoTitleConvert
= false;
295 $mw =& MagicWord
::get( 'nocontentconvert' );
296 if( $mw->matchAndRemove( $text ) ) {
297 $this->mDoContentConvert
= false;
300 // no conversion if redirecting
301 $mw =& MagicWord
::get( 'redirect' );
302 if( $mw->matchStart( $text ))
306 if($this->mNoTitleConvert
){
307 $this->mTitleDisplay
= $text;
311 if( !$this->mDoTitleConvert
) {
312 $this->mTitleDisplay
= $text;
315 if( !empty($this->mTitleDisplay
))
316 return $this->mTitleDisplay
;
319 $isredir = $wgRequest->getText( 'redirect', 'yes' );
320 $action = $wgRequest->getText( 'action' );
321 if ( $isredir == 'no' ||
$action == 'edit' ) {
325 $this->mTitleDisplay
= $this->convert($text);
326 return $this->mTitleDisplay
;
330 if( !$this->mDoContentConvert
)
333 $plang = $this->getPreferredVariant();
334 if( isset( $this->mVariantFallbacks
[$plang] ) ) {
335 $fallback = $this->mVariantFallbacks
[$plang];
337 // This sounds... bad?
341 $tarray = explode($this->mMarkup
['begin'], $text);
342 $tfirst = array_shift($tarray);
343 $text = $this->autoConvert($tfirst);
344 foreach($tarray as $txt) {
345 $marked = explode($this->mMarkup
['end'], $txt, 2);
347 $tt = explode($this->mMarkup
['flagsep'], $marked[0], 2);
349 if(sizeof($tt) == 2) {
350 $f = explode($this->mMarkup
['varsep'], $tt[0]);
353 if(array_key_exists($ff, $this->mFlags
) &&
354 !array_key_exists($this->mFlags
[$ff], $flags))
355 $flags[] = $this->mFlags
[$ff];
362 //FIXME: may cause trouble here...
363 //strip since it interferes with the parsing, plus,
364 //all spaces should be stripped in this tag anyway.
365 $rules = str_replace(' ', '', $rules);
367 $carray = $this->parseManualRule($rules, $flags);
369 if(array_key_exists($plang, $carray))
370 $disp = $carray[$plang];
371 else if(array_key_exists($fallback, $carray))
372 $disp = $carray[$fallback];
374 if(in_array('T', $flags))
375 $this->mTitleDisplay
= $disp;
379 if(in_array('A', $flags)) {
380 /* modify the conversion table for this session*/
382 /* fill in the missing variants, if any,
384 foreach($this->mVariants
as $v) {
385 if(!array_key_exists($v, $carray)) {
386 $vf = $this->getVariantFallback($v);
387 if(array_key_exists($vf, $carray))
388 $carray[$v] = $carray[$vf];
392 foreach($this->mVariants
as $vfrom) {
393 if(!array_key_exists($vfrom, $carray))
395 foreach($this->mVariants
as $vto) {
398 if(!array_key_exists($vto, $carray))
400 $this->mTables
[$vto][$carray[$vfrom]] = $carray[$vto];
404 if ( $this->mUseFss
) {
405 $this->generateFssObjects();
412 if(array_key_exists(1, $marked))
413 $text .= $this->autoConvert($marked[1]);
420 * parse the manually marked conversion rule
421 * @param string $rule the text of the rule
422 * @return array of the translation in each variant
425 function parseManualRule($rules, $flags=array()) {
427 $choice = explode($this->mMarkup
['varsep'], $rules);
429 if(sizeof($choice) == 1) {
430 /* a single choice */
431 foreach($this->mVariants
as $v)
432 $carray[$v] = $choice[0];
435 foreach($choice as $c) {
436 $v = explode($this->mMarkup
['codesep'], $c);
437 if(sizeof($v) != 2) // syntax error, skip
439 $carray[trim($v[0])] = trim($v[1]);
446 * if a language supports multiple variants, it is
447 * possible that non-existing link in one variant
448 * actually exists in another variant. this function
449 * tries to find it. See e.g. LanguageZh.php
451 * @param string $link the name of the link
452 * @param mixed $nt the title object of the link
453 * @return null the input parameters may be modified upon return
456 function findVariantLink( &$link, &$nt ) {
457 global $wgDisableLangConversion;
458 $pref = $this->getPreferredVariant();
461 $ns = $nt->getNamespace();
463 $variants = $this->autoConvertToAllVariants($link);
464 if($variants == false) //give up
466 foreach( $variants as $v ) {
467 $varnt = Title
::newFromText( $v, $ns );
468 if( $varnt && $varnt->getArticleID() > 0 ) {
470 if( !$wgDisableLangConversion )
478 * returns language specific hash options
482 function getExtraHashOptions() {
483 $variant = $this->getPreferredVariant();
484 return '!' . $variant ;
488 * get title text as defined in the body of the article text
492 function getParsedTitle() {
493 return $this->mTitleDisplay
;
497 * a write lock to the cache
501 function lockCache() {
504 for($i=0; $i<30; $i++
) {
505 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
517 function unlockCache() {
519 $wgMemc->delete($this->mCacheKey
. "lock");
524 * Load default conversion tables
525 * This method must be implemented in derived class
529 function loadDefaultTables() {
530 $name = get_class($this);
531 wfDie("Must implement loadDefaultTables() method in class $name");
535 * load conversion tables either from the cache or the disk
538 function loadTables($fromcache=true) {
540 if( $this->mTablesLoaded
)
542 $this->mTablesLoaded
= true;
544 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
545 if( !empty( $this->mTables
) ) //all done
548 // not in cache, or we need a fresh reload.
549 // we will first load the default tables
550 // then update them using things in MediaWiki:Zhconversiontable/*
551 global $wgMessageCache;
552 $this->loadDefaultTables();
553 foreach($this->mVariants
as $var) {
554 $cached = $this->parseCachedTable($var);
555 $this->mTables
[$var] = array_merge($this->mTables
[$var], $cached);
558 $this->postLoadTables();
560 if($this->lockCache()) {
561 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
562 $this->unlockCache();
564 if ( $this->mUseFss
) {
565 $this->generateFssObjects();
570 * Generate FSS objects. The FSS extension must be available.
572 function generateFssObjects() {
573 foreach ( $this->mTables
as $variant => $table ) {
574 $this->mFssObjects
[$variant] = fss_prep_replace( $table );
579 * Hook for post processig after conversion tables are loaded
582 function postLoadTables() {}
585 * Reload the conversion tables
589 function reloadTables() {
591 unset($this->mTables
);
592 $this->mTablesLoaded
= false;
593 $this->loadTables(false);
598 * parse the conversion table stored in the cache
600 * the tables should be in blocks of the following form:
608 * to make the tables more manageable, subpages are allowed
609 * and will be parsed recursively if $recursive=true
613 function parseCachedTable($code, $subpage='', $recursive=true) {
614 global $wgMessageCache;
615 static $parsed = array();
617 if(!is_object($wgMessageCache))
620 $key = 'Conversiontable/'.$code;
622 $key .= '/' . $subpage;
624 if(array_key_exists($key, $parsed))
628 $txt = $wgMessageCache->get( $key, true, true, true );
630 // get all subpage links of the form
631 // [[MediaWiki:conversiontable/zh-xx/...|...]]
632 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
633 $subs = explode('[[', $txt);
635 foreach( $subs as $sub ) {
636 $link = explode(']]', $sub, 2);
637 if(count($link) != 2)
639 $b = explode('|', $link[0]);
640 $b = explode('/', trim($b[0]), 3);
646 if($b[0] == $linkhead && $b[1] == $code) {
647 $sublinks[] = $sublink;
652 // parse the mappings in this page
653 $blocks = explode($this->mMarkup
['begin'], $txt);
654 array_shift($blocks);
656 foreach($blocks as $block) {
657 $mappings = explode($this->mMarkup
['end'], $block, 2);
658 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
659 $table = explode( ';', $stripped );
660 foreach( $table as $t ) {
661 $m = explode( '=>', $t );
662 if( count( $m ) != 2)
664 // trim any trailling comments starting with '//'
665 $tt = explode('//', $m[1], 2);
666 $ret[trim($m[0])] = trim($tt[0]);
669 $parsed[$key] = true;
672 // recursively parse the subpages
674 foreach($sublinks as $link) {
675 $s = $this->parseCachedTable($code, $link, $recursive);
676 $ret = array_merge($ret, $s);
680 if ($this->mUcfirst
) {
681 foreach ($ret as $k => $v) {
682 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
689 * Enclose a string with the "no conversion" tag. This is used by
690 * various functions in the Parser
692 * @param string $text text to be tagged for no conversion
693 * @return string the tagged text
695 function markNoConversion($text, $noParse=false) {
696 # don't mark if already marked
697 if(strpos($text, $this->mMarkup
['begin']) ||
698 strpos($text, $this->mMarkup
['end']))
701 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
706 * convert the sorting key for category links. this should make different
707 * keys that are variants of each other map to the same key
709 function convertCategoryKey( $key ) {
713 * hook to refresh the cache of conversion tables when
714 * MediaWiki:conversiontable* is updated
717 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
718 $titleobj = $article->getTitle();
719 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
721 global $wgContLang; // should be an LanguageZh.
722 if(get_class($wgContLang) != 'languagezh')
725 $title = $titleobj->getDBkey();
726 $t = explode('/', $title, 3);
728 if( $c > 1 && $t[0] == 'Conversiontable' ) {
729 if(in_array($t[1], $this->mVariants
)) {
730 $this->reloadTables();
737 function setNoTitleConvert(){
738 $this->mNoTitleConvert
= true;