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(),
41 global $wgLegalTitleChars;
42 $this->mLangObj
= $langobj;
43 $this->mMainLanguageCode
= $maincode;
44 $this->mVariants
= $variants;
45 $this->mVariantFallbacks
= $variantfallbacks;
46 $this->mCacheKey
= wfMemcKey( 'conversiontables' );
47 $m = array('begin'=>'-{', 'flagsep'=>'|', 'codesep'=>':',
48 'varsep'=>';', 'end'=>'}-');
49 $this->mMarkup
= array_merge($m, $markup);
50 $f = array('A'=>'A', 'T'=>'T');
51 $this->mFlags
= array_merge($f, $flags);
52 if ( function_exists( 'fss_prep_replace' ) ) {
53 $this->mUseFss
= true;
60 function getVariants() {
61 return $this->mVariants
;
65 * in case some variant is not defined in the markup, we need
66 * to have some fallback. for example, in zh, normally people
67 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
68 * when zh-sg is preferred but not defined, we will pick zh-cn
69 * in this case. right now this is only used by zh.
71 * @param string $v the language code of the variant
72 * @return string the code of the fallback language or false if there is no fallback
75 function getVariantFallback($v) {
76 return $this->mVariantFallbacks
[$v];
81 * get preferred language variants.
82 * @param boolean $fromUser Get it from $wgUser's preferences
83 * @return string the preferred language code
86 function getPreferredVariant( $fromUser = true ) {
87 global $wgUser, $wgRequest;
89 if($this->mPreferredVariant
)
90 return $this->mPreferredVariant
;
92 // see if the preference is set in the request
93 $req = $wgRequest->getText( 'variant' );
94 if( in_array( $req, $this->mVariants
) ) {
95 $this->mPreferredVariant
= $req;
99 // get language variant preference from logged in users
100 // Don't call this on stub objects because that causes infinite
101 // recursion during initialisation
102 if( $fromUser && $wgUser->isLoggedIn() ) {
103 $this->mPreferredVariant
= $wgUser->getOption('variant');
104 return $this->mPreferredVariant
;
107 # FIXME rewrite code for parsing http header. The current code
108 # is written specific for detecting zh- variants
109 if( !$this->mPreferredVariant
) {
110 // see if some supported language variant is set in the
111 // http header, but we don't set the mPreferredVariant
112 // variable in case this is called before the user's
113 // preference is loaded
114 $pv=$this->mMainLanguageCode
;
115 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
116 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
117 $zh = strstr($header, 'zh-');
119 $pv = substr($zh,0,5);
127 * dictionary-based conversion
129 * @param string $text the text to be converted
130 * @param string $toVariant the target language code
131 * @return string the converted text
134 function autoConvert($text, $toVariant=false) {
135 $fname="LanguageConverter::autoConvert";
137 wfProfileIn( $fname );
139 if(!$this->mTablesLoaded
)
143 $toVariant = $this->getPreferredVariant();
144 if(!in_array($toVariant, $this->mVariants
))
147 /* we convert everything except:
148 1. html markups (anything between < and >)
150 3. place holders created by the parser
153 if (isset($wgParser))
154 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
158 // this one is needed when the text is inside an html markup
159 $htmlfix = '|<[^>]+$|^[^<>]*>';
161 // disable convert to variants between <code></code> tags
162 $codefix = '<code>.+?<\/code>|';
164 $reg = '/'.$codefix.'<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
166 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
168 $m = array_shift($matches);
170 $ret = $this->translate($m[0], $toVariant);
171 $mstart = $m[1]+
strlen($m[0]);
172 foreach($matches as $m) {
173 $ret .= substr($text, $mstart, $m[1]-$mstart);
174 $ret .= $this->translate($m[0], $toVariant);
175 $mstart = $m[1] +
strlen($m[0]);
177 wfProfileOut( $fname );
182 * Translate a string to a variant
183 * Doesn't process markup or do any of that other stuff, for that use convert()
185 * @param string $text Text to convert
186 * @param string $variant Variant language code
187 * @return string Translated text
189 function translate( $text, $variant ) {
190 if( !$this->mTablesLoaded
)
192 if ( $this->mUseFss
) {
193 return fss_exec_replace( $this->mFssObjects
[$variant], $text );
195 return strtr( $text, $this->mTables
[$variant] );
200 * convert text to all supported variants
202 * @param string $text the text to be converted
203 * @return array of string
206 function autoConvertToAllVariants($text) {
207 $fname="LanguageConverter::autoConvertToAllVariants";
208 wfProfileIn( $fname );
209 if( !$this->mTablesLoaded
)
213 foreach($this->mVariants
as $variant) {
214 $ret[$variant] = $this->translate($text, $variant);
217 wfProfileOut( $fname );
222 * convert link text to all supported variants
224 * @param string $text the text to be converted
225 * @return array of string
228 function convertLinkToAllVariants($text) {
229 if( !$this->mTablesLoaded
)
233 $tarray = explode($this->mMarkup
['begin'], $text);
234 $tfirst = array_shift($tarray);
236 foreach($this->mVariants
as $variant)
237 $ret[$variant] = $this->translate($tfirst,$variant);
239 foreach($tarray as $txt) {
240 $marked = explode($this->mMarkup
['end'], $txt, 2);
242 foreach($this->mVariants
as $variant){
243 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
244 if(array_key_exists(1, $marked))
245 $ret[$variant] .= $this->translate($marked[1],$variant);
255 * Convert text using a parser object for context
257 function parserConvert( $text, &$parser ) {
258 global $wgDisableLangConversion;
259 /* don't do anything if this is the conversion table */
260 if ( $parser->mTitle
->getNamespace() == NS_MEDIAWIKI
&&
261 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
266 if($wgDisableLangConversion)
269 $text = $this->convert( $text );
270 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
275 * convert text to different variants of a language. the automatic
276 * conversion is done in autoConvert(). here we parse the text
277 * marked with -{}-, which specifies special conversions of the
278 * text that can not be accomplished in autoConvert()
280 * syntax of the markup:
281 * -{code1:text1;code2:text2;...}- or
282 * -{text}- in which case no conversion should take place for text
284 * @param string $text text to be converted
285 * @param bool $isTitle whether this conversion is for the article title
286 * @return string converted text
289 function convert( $text , $isTitle=false) {
290 $mw =& MagicWord
::get( 'notitleconvert' );
291 if( $mw->matchAndRemove( $text ) )
292 $this->mDoTitleConvert
= false;
294 $mw =& MagicWord
::get( 'nocontentconvert' );
295 if( $mw->matchAndRemove( $text ) ) {
296 $this->mDoContentConvert
= false;
299 // no conversion if redirecting
300 $mw =& MagicWord
::get( 'redirect' );
301 if( $mw->matchStart( $text ))
305 if($this->mNoTitleConvert
){
306 $this->mTitleDisplay
= $text;
310 if( !$this->mDoTitleConvert
) {
311 $this->mTitleDisplay
= $text;
316 $isredir = $wgRequest->getText( 'redirect', 'yes' );
317 $action = $wgRequest->getText( 'action' );
318 if ( $isredir == 'no' ||
$action == 'edit' ) {
322 $this->mTitleDisplay
= $this->convert($text);
323 return $this->mTitleDisplay
;
327 if( !$this->mDoContentConvert
)
330 $plang = $this->getPreferredVariant();
331 if( isset( $this->mVariantFallbacks
[$plang] ) ) {
332 $fallback = $this->mVariantFallbacks
[$plang];
334 // This sounds... bad?
338 $tarray = explode($this->mMarkup
['begin'], $text);
339 $tfirst = array_shift($tarray);
340 $text = $this->autoConvert($tfirst);
341 foreach($tarray as $txt) {
342 $marked = explode($this->mMarkup
['end'], $txt, 2);
344 $tt = explode($this->mMarkup
['flagsep'], $marked[0], 2);
346 if(sizeof($tt) == 2) {
347 $f = explode($this->mMarkup
['varsep'], $tt[0]);
350 if(array_key_exists($ff, $this->mFlags
) &&
351 !array_key_exists($this->mFlags
[$ff], $flags))
352 $flags[] = $this->mFlags
[$ff];
359 //FIXME: may cause trouble here...
360 //strip since it interferes with the parsing, plus,
361 //all spaces should be stripped in this tag anyway.
362 $rules = str_replace(' ', '', $rules);
364 $carray = $this->parseManualRule($rules, $flags);
366 if(array_key_exists($plang, $carray))
367 $disp = $carray[$plang];
368 else if(array_key_exists($fallback, $carray))
369 $disp = $carray[$fallback];
371 if(in_array('T', $flags))
372 $this->mTitleDisplay
= $disp;
376 if(in_array('A', $flags)) {
377 /* modify the conversion table for this session*/
379 /* fill in the missing variants, if any,
381 foreach($this->mVariants
as $v) {
382 if(!array_key_exists($v, $carray)) {
383 $vf = $this->getVariantFallback($v);
384 if(array_key_exists($vf, $carray))
385 $carray[$v] = $carray[$vf];
389 foreach($this->mVariants
as $vfrom) {
390 if(!array_key_exists($vfrom, $carray))
392 foreach($this->mVariants
as $vto) {
395 if(!array_key_exists($vto, $carray))
397 $this->mTables
[$vto][$carray[$vfrom]] = $carray[$vto];
401 if ( $this->mUseFss
) {
402 $this->generateFssObjects();
409 if(array_key_exists(1, $marked))
410 $text .= $this->autoConvert($marked[1]);
417 * parse the manually marked conversion rule
418 * @param string $rule the text of the rule
419 * @return array of the translation in each variant
422 function parseManualRule($rules, $flags=array()) {
424 $choice = explode($this->mMarkup
['varsep'], $rules);
426 if(sizeof($choice) == 1) {
427 /* a single choice */
428 foreach($this->mVariants
as $v)
429 $carray[$v] = $choice[0];
432 foreach($choice as $c) {
433 $v = explode($this->mMarkup
['codesep'], $c);
434 if(sizeof($v) != 2) // syntax error, skip
436 $carray[trim($v[0])] = trim($v[1]);
443 * if a language supports multiple variants, it is
444 * possible that non-existing link in one variant
445 * actually exists in another variant. this function
446 * tries to find it. See e.g. LanguageZh.php
448 * @param string $link the name of the link
449 * @param mixed $nt the title object of the link
450 * @return null the input parameters may be modified upon return
453 function findVariantLink( &$link, &$nt ) {
454 global $wgDisableLangConversion;
455 $pref = $this->getPreferredVariant();
458 $ns = $nt->getNamespace();
460 $variants = $this->autoConvertToAllVariants($link);
461 if($variants == false) //give up
463 foreach( $variants as $v ) {
464 $varnt = Title
::newFromText( $v, $ns );
465 if( $varnt && $varnt->getArticleID() > 0 ) {
467 if( !$wgDisableLangConversion )
475 * returns language specific hash options
479 function getExtraHashOptions() {
480 $variant = $this->getPreferredVariant();
481 return '!' . $variant ;
485 * get title text as defined in the body of the article text
489 function getParsedTitle() {
490 return $this->mTitleDisplay
;
494 * a write lock to the cache
498 function lockCache() {
501 for($i=0; $i<30; $i++
) {
502 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
514 function unlockCache() {
516 $wgMemc->delete($this->mCacheKey
. "lock");
521 * Load default conversion tables
522 * This method must be implemented in derived class
526 function loadDefaultTables() {
527 $name = get_class($this);
528 wfDie("Must implement loadDefaultTables() method in class $name");
532 * load conversion tables either from the cache or the disk
535 function loadTables($fromcache=true) {
537 if( $this->mTablesLoaded
)
539 $this->mTablesLoaded
= true;
541 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
542 if( !empty( $this->mTables
) ) //all done
545 // not in cache, or we need a fresh reload.
546 // we will first load the default tables
547 // then update them using things in MediaWiki:Zhconversiontable/*
548 global $wgMessageCache;
549 $this->loadDefaultTables();
550 foreach($this->mVariants
as $var) {
551 $cached = $this->parseCachedTable($var);
552 $this->mTables
[$var] = array_merge($this->mTables
[$var], $cached);
555 $this->postLoadTables();
557 if($this->lockCache()) {
558 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
559 $this->unlockCache();
561 if ( $this->mUseFss
) {
562 $this->generateFssObjects();
567 * Generate FSS objects. The FSS extension must be available.
569 function generateFssObjects() {
570 foreach ( $this->mTables
as $variant => $table ) {
571 $this->mFssObjects
[$variant] = fss_prep_replace( $table );
576 * Hook for post processig after conversion tables are loaded
579 function postLoadTables() {}
582 * Reload the conversion tables
586 function reloadTables() {
588 unset($this->mTables
);
589 $this->mTablesLoaded
= false;
590 $this->loadTables(false);
595 * parse the conversion table stored in the cache
597 * the tables should be in blocks of the following form:
605 * to make the tables more manageable, subpages are allowed
606 * and will be parsed recursively if $recursive=true
610 function parseCachedTable($code, $subpage='', $recursive=true) {
611 global $wgMessageCache;
612 static $parsed = array();
614 if(!is_object($wgMessageCache))
617 $key = 'Conversiontable/'.$code;
619 $key .= '/' . $subpage;
621 if(array_key_exists($key, $parsed))
625 $txt = $wgMessageCache->get( $key, true, true, true );
627 // get all subpage links of the form
628 // [[MediaWiki:conversiontable/zh-xx/...|...]]
629 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
630 $subs = explode('[[', $txt);
632 foreach( $subs as $sub ) {
633 $link = explode(']]', $sub, 2);
634 if(count($link) != 2)
636 $b = explode('|', $link[0]);
637 $b = explode('/', trim($b[0]), 3);
643 if($b[0] == $linkhead && $b[1] == $code) {
644 $sublinks[] = $sublink;
649 // parse the mappings in this page
650 $blocks = explode($this->mMarkup
['begin'], $txt);
651 array_shift($blocks);
653 foreach($blocks as $block) {
654 $mappings = explode($this->mMarkup
['end'], $block, 2);
655 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
656 $table = explode( ';', $stripped );
657 foreach( $table as $t ) {
658 $m = explode( '=>', $t );
659 if( count( $m ) != 2)
661 // trim any trailling comments starting with '//'
662 $tt = explode('//', $m[1], 2);
663 $ret[trim($m[0])] = trim($tt[0]);
666 $parsed[$key] = true;
669 // recursively parse the subpages
671 foreach($sublinks as $link) {
672 $s = $this->parseCachedTable($code, $link, $recursive);
673 $ret = array_merge($ret, $s);
677 if ($this->mUcfirst
) {
678 foreach ($ret as $k => $v) {
679 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
686 * Enclose a string with the "no conversion" tag. This is used by
687 * various functions in the Parser
689 * @param string $text text to be tagged for no conversion
690 * @return string the tagged text
692 function markNoConversion($text, $noParse=false) {
693 # don't mark if already marked
694 if(strpos($text, $this->mMarkup
['begin']) ||
695 strpos($text, $this->mMarkup
['end']))
698 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
703 * convert the sorting key for category links. this should make different
704 * keys that are variants of each other map to the same key
706 function convertCategoryKey( $key ) {
710 * hook to refresh the cache of conversion tables when
711 * MediaWiki:conversiontable* is updated
714 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
715 $titleobj = $article->getTitle();
716 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
718 global $wgContLang; // should be an LanguageZh.
719 if(get_class($wgContLang) != 'languagezh')
722 $title = $titleobj->getDBkey();
723 $t = explode('/', $title, 3);
725 if( $c > 1 && $t[0] == 'Conversiontable' ) {
726 if(in_array($t[1], $this->mVariants
)) {
727 $this->reloadTables();
734 function setNoTitleConvert(){
735 $this->mNoTitleConvert
= true;