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;
23 var $mNoTitleConvert = false;
27 * @param string $maincode the main language code of this language
28 * @param array $variants the supported variants of this language
29 * @param array $variantfallback the fallback language of each variant
30 * @param array $markup array defining the markup used for manual conversion
31 * @param array $flags array defining the custom strings that maps to the flags
34 function __construct($langobj, $maincode,
36 $variantfallbacks=array(),
39 global $wgLegalTitleChars;
40 $this->mLangObj
= $langobj;
41 $this->mMainLanguageCode
= $maincode;
42 $this->mVariants
= $variants;
43 $this->mVariantFallbacks
= $variantfallbacks;
44 $this->mCacheKey
= wfMemcKey( 'conversiontables' );
45 $m = array('begin'=>'-{', 'flagsep'=>'|', 'codesep'=>':',
46 'varsep'=>';', 'end'=>'}-');
47 $this->mMarkup
= array_merge($m, $markup);
48 $f = array('A'=>'A', 'T'=>'T');
49 $this->mFlags
= array_merge($f, $flags);
55 function getVariants() {
56 return $this->mVariants
;
60 * in case some variant is not defined in the markup, we need
61 * to have some fallback. for example, in zh, normally people
62 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
63 * when zh-sg is preferred but not defined, we will pick zh-cn
64 * in this case. right now this is only used by zh.
66 * @param string $v the language code of the variant
67 * @return string the code of the fallback language or false if there is no fallback
70 function getVariantFallback($v) {
71 return $this->mVariantFallbacks
[$v];
76 * get preferred language variants.
77 * @param boolean $fromUser Get it from $wgUser's preferences
78 * @return string the preferred language code
81 function getPreferredVariant( $fromUser = true ) {
82 global $wgUser, $wgRequest;
84 if($this->mPreferredVariant
)
85 return $this->mPreferredVariant
;
87 // see if the preference is set in the request
88 $req = $wgRequest->getText( 'variant' );
89 if( in_array( $req, $this->mVariants
) ) {
90 $this->mPreferredVariant
= $req;
94 // check the syntax /code/ArticleTitle
95 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
96 if(in_array($scriptBase,$this->mVariants
)){
97 $this->mPreferredVariant
= $scriptBase;
98 return $this->mPreferredVariant
;
101 // get language variant preference from logged in users
102 // Don't call this on stub objects because that causes infinite
103 // recursion during initialisation
104 if( $fromUser && $wgUser->isLoggedIn() ) {
105 $this->mPreferredVariant
= $wgUser->getOption('variant');
106 return $this->mPreferredVariant
;
109 # FIXME rewrite code for parsing http header. The current code
110 # is written specific for detecting zh- variants
111 if( !$this->mPreferredVariant
) {
112 // see if some supported language variant is set in the
113 // http header, but we don't set the mPreferredVariant
114 // variable in case this is called before the user's
115 // preference is loaded
116 $pv=$this->mMainLanguageCode
;
117 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
118 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
119 $zh = strstr($header, $pv.'-');
121 $pv = substr($zh,0,5);
129 * dictionary-based conversion
131 * @param string $text the text to be converted
132 * @param string $toVariant the target language code
133 * @return string the converted text
136 function autoConvert($text, $toVariant=false) {
137 $fname="LanguageConverter::autoConvert";
139 wfProfileIn( $fname );
141 if(!$this->mTablesLoaded
)
145 $toVariant = $this->getPreferredVariant();
146 if(!in_array($toVariant, $this->mVariants
))
149 /* we convert everything except:
150 1. html markups (anything between < and >)
152 3. place holders created by the parser
155 if (isset($wgParser))
156 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
160 // this one is needed when the text is inside an html markup
161 $htmlfix = '|<[^>]+$|^[^<>]*>';
163 // disable convert to variants between <code></code> tags
164 $codefix = '<code>.+?<\/code>|';
166 $reg = '/'.$codefix.'<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
168 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
170 $m = array_shift($matches);
172 $ret = $this->translate($m[0], $toVariant);
173 $mstart = $m[1]+
strlen($m[0]);
174 foreach($matches as $m) {
175 $ret .= substr($text, $mstart, $m[1]-$mstart);
176 $ret .= $this->translate($m[0], $toVariant);
177 $mstart = $m[1] +
strlen($m[0]);
179 wfProfileOut( $fname );
184 * Translate a string to a variant
185 * Doesn't process markup or do any of that other stuff, for that use convert()
187 * @param string $text Text to convert
188 * @param string $variant Variant language code
189 * @return string Translated text
191 function translate( $text, $variant ) {
192 wfProfileIn( __METHOD__
);
193 if( !$this->mTablesLoaded
)
195 $text = $this->mTables
[$variant]->replace( $text );
196 wfProfileOut( __METHOD__
);
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;
317 $isredir = $wgRequest->getText( 'redirect', 'yes' );
318 $action = $wgRequest->getText( 'action' );
319 if ( $isredir == 'no' ||
$action == 'edit' ) {
323 $this->mTitleDisplay
= $this->convert($text);
324 return $this->mTitleDisplay
;
328 if( !$this->mDoContentConvert
)
331 $plang = $this->getPreferredVariant();
332 if( isset( $this->mVariantFallbacks
[$plang] ) ) {
333 $fallback = $this->mVariantFallbacks
[$plang];
335 // This sounds... bad?
339 $tarray = explode($this->mMarkup
['begin'], $text);
340 $tfirst = array_shift($tarray);
341 $text = $this->autoConvert($tfirst);
342 foreach($tarray as $txt) {
343 $marked = explode($this->mMarkup
['end'], $txt, 2);
345 $tt = explode($this->mMarkup
['flagsep'], $marked[0], 2);
347 if(sizeof($tt) == 2) {
348 $f = explode($this->mMarkup
['varsep'], $tt[0]);
351 if(array_key_exists($ff, $this->mFlags
) &&
352 !array_key_exists($this->mFlags
[$ff], $flags))
353 $flags[] = $this->mFlags
[$ff];
360 //FIXME: may cause trouble here...
361 //strip since it interferes with the parsing, plus,
362 //all spaces should be stripped in this tag anyway.
363 $rules = str_replace(' ', '', $rules);
365 $carray = $this->parseManualRule($rules, $flags);
367 if(array_key_exists($plang, $carray))
368 $disp = $carray[$plang];
369 else if(array_key_exists($fallback, $carray))
370 $disp = $carray[$fallback];
372 if(in_array('T', $flags))
373 $this->mTitleDisplay
= $disp;
377 if(in_array('A', $flags)) {
378 /* modify the conversion table for this session*/
380 /* fill in the missing variants, if any,
382 foreach($this->mVariants
as $v) {
383 if(!array_key_exists($v, $carray)) {
384 $vf = $this->getVariantFallback($v);
385 if(array_key_exists($vf, $carray))
386 $carray[$v] = $carray[$vf];
390 foreach($this->mVariants
as $vfrom) {
391 if(!array_key_exists($vfrom, $carray))
393 foreach($this->mVariants
as $vto) {
396 if(!array_key_exists($vto, $carray))
398 $this->mTables
[$vto]->setPair($carray[$vfrom], $carray[$vto]);
406 if(array_key_exists(1, $marked))
407 $text .= $this->autoConvert($marked[1]);
414 * parse the manually marked conversion rule
415 * @param string $rule the text of the rule
416 * @return array of the translation in each variant
419 function parseManualRule($rules, $flags=array()) {
421 $choice = explode($this->mMarkup
['varsep'], $rules);
423 if(sizeof($choice) == 1) {
424 /* a single choice */
425 foreach($this->mVariants
as $v)
426 $carray[$v] = $choice[0];
429 foreach($choice as $c) {
430 $v = explode($this->mMarkup
['codesep'], $c);
431 if(sizeof($v) != 2) // syntax error, skip
433 $carray[trim($v[0])] = trim($v[1]);
440 * if a language supports multiple variants, it is
441 * possible that non-existing link in one variant
442 * actually exists in another variant. this function
443 * tries to find it. See e.g. LanguageZh.php
445 * @param string $link the name of the link
446 * @param mixed $nt the title object of the link
447 * @return null the input parameters may be modified upon return
450 function findVariantLink( &$link, &$nt ) {
451 global $wgDisableLangConversion;
452 $pref = $this->getPreferredVariant();
455 $ns = $nt->getNamespace();
457 $variants = $this->autoConvertToAllVariants($link);
458 if($variants == false) //give up
460 foreach( $variants as $v ) {
461 $varnt = Title
::newFromText( $v, $ns );
462 if( $varnt && $varnt->getArticleID() > 0 ) {
464 if( !$wgDisableLangConversion )
472 * returns language specific hash options
476 function getExtraHashOptions() {
477 $variant = $this->getPreferredVariant();
478 return '!' . $variant ;
482 * get title text as defined in the body of the article text
486 function getParsedTitle() {
487 return $this->mTitleDisplay
;
491 * a write lock to the cache
495 function lockCache() {
498 for($i=0; $i<30; $i++
) {
499 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
511 function unlockCache() {
513 $wgMemc->delete($this->mCacheKey
. "lock");
518 * Load default conversion tables
519 * This method must be implemented in derived class
523 function loadDefaultTables() {
524 $name = get_class($this);
525 wfDie("Must implement loadDefaultTables() method in class $name");
529 * load conversion tables either from the cache or the disk
532 function loadTables($fromcache=true) {
534 if( $this->mTablesLoaded
)
536 wfProfileIn( __METHOD__
);
537 $this->mTablesLoaded
= true;
538 $this->mTables
= false;
540 wfProfileIn( __METHOD__
.'-cache' );
541 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
542 wfProfileOut( __METHOD__
.'-cache' );
544 if ( !$this->mTables ||
!isset( $this->mTables
['VERSION 2'] ) ) {
545 wfProfileIn( __METHOD__
.'-recache' );
546 // not in cache, or we need a fresh reload.
547 // we will first load the default tables
548 // then update them using things in MediaWiki:Zhconversiontable/*
549 global $wgMessageCache;
550 $this->loadDefaultTables();
551 foreach($this->mVariants
as $var) {
552 $cached = $this->parseCachedTable($var);
553 $this->mTables
[$var]->mergeArray($cached);
556 $this->postLoadTables();
557 $this->mTables
['VERSION 2'] = true;
559 if($this->lockCache()) {
560 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
561 $this->unlockCache();
563 wfProfileOut( __METHOD__
.'-recache' );
565 wfProfileOut( __METHOD__
);
569 * Hook for post processig after conversion tables are loaded
572 function postLoadTables() {}
575 * Reload the conversion tables
579 function reloadTables() {
581 unset($this->mTables
);
582 $this->mTablesLoaded
= false;
583 $this->loadTables(false);
588 * parse the conversion table stored in the cache
590 * the tables should be in blocks of the following form:
598 * to make the tables more manageable, subpages are allowed
599 * and will be parsed recursively if $recursive=true
603 function parseCachedTable($code, $subpage='', $recursive=true) {
604 global $wgMessageCache;
605 static $parsed = array();
607 if(!is_object($wgMessageCache))
610 $key = 'Conversiontable/'.$code;
612 $key .= '/' . $subpage;
614 if(array_key_exists($key, $parsed))
618 $txt = $wgMessageCache->get( $key, true, true, true );
620 // get all subpage links of the form
621 // [[MediaWiki:conversiontable/zh-xx/...|...]]
622 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
623 $subs = explode('[[', $txt);
625 foreach( $subs as $sub ) {
626 $link = explode(']]', $sub, 2);
627 if(count($link) != 2)
629 $b = explode('|', $link[0]);
630 $b = explode('/', trim($b[0]), 3);
636 if($b[0] == $linkhead && $b[1] == $code) {
637 $sublinks[] = $sublink;
642 // parse the mappings in this page
643 $blocks = explode($this->mMarkup
['begin'], $txt);
644 array_shift($blocks);
646 foreach($blocks as $block) {
647 $mappings = explode($this->mMarkup
['end'], $block, 2);
648 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
649 $table = explode( ';', $stripped );
650 foreach( $table as $t ) {
651 $m = explode( '=>', $t );
652 if( count( $m ) != 2)
654 // trim any trailling comments starting with '//'
655 $tt = explode('//', $m[1], 2);
656 $ret[trim($m[0])] = trim($tt[0]);
659 $parsed[$key] = true;
662 // recursively parse the subpages
664 foreach($sublinks as $link) {
665 $s = $this->parseCachedTable($code, $link, $recursive);
666 $ret = array_merge($ret, $s);
670 if ($this->mUcfirst
) {
671 foreach ($ret as $k => $v) {
672 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
679 * Enclose a string with the "no conversion" tag. This is used by
680 * various functions in the Parser
682 * @param string $text text to be tagged for no conversion
683 * @return string the tagged text
685 function markNoConversion($text, $noParse=false) {
686 # don't mark if already marked
687 if(strpos($text, $this->mMarkup
['begin']) ||
688 strpos($text, $this->mMarkup
['end']))
691 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
696 * convert the sorting key for category links. this should make different
697 * keys that are variants of each other map to the same key
699 function convertCategoryKey( $key ) {
703 * hook to refresh the cache of conversion tables when
704 * MediaWiki:conversiontable* is updated
707 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
708 $titleobj = $article->getTitle();
709 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
711 global $wgContLang; // should be an LanguageZh.
712 if(get_class($wgContLang) != 'languagezh')
715 $title = $titleobj->getDBkey();
716 $t = explode('/', $title, 3);
718 if( $c > 1 && $t[0] == 'Conversiontable' ) {
719 if(in_array($t[1], $this->mVariants
)) {
720 $this->reloadTables();
727 function setNoTitleConvert(){
728 $this->mNoTitleConvert
= true;