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 // check the syntax /code/ArticleTitle
100 $script = $_SERVER['SCRIPT_NAME'];
101 $variants = implode('|',$this->mVariants
);
102 if(preg_match("/($variants)$/",$script,$matches)){
103 $this->mPreferredVariant
= $matches[1];
104 return $this->mPreferredVariant
;
107 // get language variant preference from logged in users
108 // Don't call this on stub objects because that causes infinite
109 // recursion during initialisation
110 if( $fromUser && $wgUser->isLoggedIn() ) {
111 $this->mPreferredVariant
= $wgUser->getOption('variant');
112 return $this->mPreferredVariant
;
115 # FIXME rewrite code for parsing http header. The current code
116 # is written specific for detecting zh- variants
117 if( !$this->mPreferredVariant
) {
118 // see if some supported language variant is set in the
119 // http header, but we don't set the mPreferredVariant
120 // variable in case this is called before the user's
121 // preference is loaded
122 $pv=$this->mMainLanguageCode
;
123 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
124 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
125 $zh = strstr($header, 'zh-');
127 $pv = substr($zh,0,5);
135 * dictionary-based conversion
137 * @param string $text the text to be converted
138 * @param string $toVariant the target language code
139 * @return string the converted text
142 function autoConvert($text, $toVariant=false) {
143 $fname="LanguageConverter::autoConvert";
145 wfProfileIn( $fname );
147 if(!$this->mTablesLoaded
)
151 $toVariant = $this->getPreferredVariant();
152 if(!in_array($toVariant, $this->mVariants
))
155 /* we convert everything except:
156 1. html markups (anything between < and >)
158 3. place holders created by the parser
161 if (isset($wgParser))
162 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
166 // this one is needed when the text is inside an html markup
167 $htmlfix = '|<[^>]+$|^[^<>]*>';
169 // disable convert to variants between <code></code> tags
170 $codefix = '<code>.+?<\/code>|';
172 $reg = '/'.$codefix.'<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
174 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
176 $m = array_shift($matches);
178 $ret = $this->translate($m[0], $toVariant);
179 $mstart = $m[1]+
strlen($m[0]);
180 foreach($matches as $m) {
181 $ret .= substr($text, $mstart, $m[1]-$mstart);
182 $ret .= $this->translate($m[0], $toVariant);
183 $mstart = $m[1] +
strlen($m[0]);
185 wfProfileOut( $fname );
190 * Translate a string to a variant
191 * Doesn't process markup or do any of that other stuff, for that use convert()
193 * @param string $text Text to convert
194 * @param string $variant Variant language code
195 * @return string Translated text
197 function translate( $text, $variant ) {
198 if( !$this->mTablesLoaded
)
200 if ( $this->mUseFss
) {
201 return fss_exec_replace( $this->mFssObjects
[$variant], $text );
203 return strtr( $text, $this->mTables
[$variant] );
208 * convert text to all supported variants
210 * @param string $text the text to be converted
211 * @return array of string
214 function autoConvertToAllVariants($text) {
215 $fname="LanguageConverter::autoConvertToAllVariants";
216 wfProfileIn( $fname );
217 if( !$this->mTablesLoaded
)
221 foreach($this->mVariants
as $variant) {
222 $ret[$variant] = $this->translate($text, $variant);
225 wfProfileOut( $fname );
230 * convert link text to all supported variants
232 * @param string $text the text to be converted
233 * @return array of string
236 function convertLinkToAllVariants($text) {
237 if( !$this->mTablesLoaded
)
241 $tarray = explode($this->mMarkup
['begin'], $text);
242 $tfirst = array_shift($tarray);
244 foreach($this->mVariants
as $variant)
245 $ret[$variant] = $this->translate($tfirst,$variant);
247 foreach($tarray as $txt) {
248 $marked = explode($this->mMarkup
['end'], $txt, 2);
250 foreach($this->mVariants
as $variant){
251 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
252 if(array_key_exists(1, $marked))
253 $ret[$variant] .= $this->translate($marked[1],$variant);
263 * Convert text using a parser object for context
265 function parserConvert( $text, &$parser ) {
266 global $wgDisableLangConversion;
267 /* don't do anything if this is the conversion table */
268 if ( $parser->mTitle
->getNamespace() == NS_MEDIAWIKI
&&
269 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
274 if($wgDisableLangConversion)
277 $text = $this->convert( $text );
278 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
283 * convert text to different variants of a language. the automatic
284 * conversion is done in autoConvert(). here we parse the text
285 * marked with -{}-, which specifies special conversions of the
286 * text that can not be accomplished in autoConvert()
288 * syntax of the markup:
289 * -{code1:text1;code2:text2;...}- or
290 * -{text}- in which case no conversion should take place for text
292 * @param string $text text to be converted
293 * @param bool $isTitle whether this conversion is for the article title
294 * @return string converted text
297 function convert( $text , $isTitle=false) {
298 $mw =& MagicWord
::get( 'notitleconvert' );
299 if( $mw->matchAndRemove( $text ) )
300 $this->mDoTitleConvert
= false;
302 $mw =& MagicWord
::get( 'nocontentconvert' );
303 if( $mw->matchAndRemove( $text ) ) {
304 $this->mDoContentConvert
= false;
307 // no conversion if redirecting
308 $mw =& MagicWord
::get( 'redirect' );
309 if( $mw->matchStart( $text ))
313 if($this->mNoTitleConvert
){
314 $this->mTitleDisplay
= $text;
318 if( !$this->mDoTitleConvert
) {
319 $this->mTitleDisplay
= $text;
324 $isredir = $wgRequest->getText( 'redirect', 'yes' );
325 $action = $wgRequest->getText( 'action' );
326 if ( $isredir == 'no' ||
$action == 'edit' ) {
330 $this->mTitleDisplay
= $this->convert($text);
331 return $this->mTitleDisplay
;
335 if( !$this->mDoContentConvert
)
338 $plang = $this->getPreferredVariant();
339 if( isset( $this->mVariantFallbacks
[$plang] ) ) {
340 $fallback = $this->mVariantFallbacks
[$plang];
342 // This sounds... bad?
346 $tarray = explode($this->mMarkup
['begin'], $text);
347 $tfirst = array_shift($tarray);
348 $text = $this->autoConvert($tfirst);
349 foreach($tarray as $txt) {
350 $marked = explode($this->mMarkup
['end'], $txt, 2);
352 $tt = explode($this->mMarkup
['flagsep'], $marked[0], 2);
354 if(sizeof($tt) == 2) {
355 $f = explode($this->mMarkup
['varsep'], $tt[0]);
358 if(array_key_exists($ff, $this->mFlags
) &&
359 !array_key_exists($this->mFlags
[$ff], $flags))
360 $flags[] = $this->mFlags
[$ff];
367 //FIXME: may cause trouble here...
368 //strip since it interferes with the parsing, plus,
369 //all spaces should be stripped in this tag anyway.
370 $rules = str_replace(' ', '', $rules);
372 $carray = $this->parseManualRule($rules, $flags);
374 if(array_key_exists($plang, $carray))
375 $disp = $carray[$plang];
376 else if(array_key_exists($fallback, $carray))
377 $disp = $carray[$fallback];
379 if(in_array('T', $flags))
380 $this->mTitleDisplay
= $disp;
384 if(in_array('A', $flags)) {
385 /* modify the conversion table for this session*/
387 /* fill in the missing variants, if any,
389 foreach($this->mVariants
as $v) {
390 if(!array_key_exists($v, $carray)) {
391 $vf = $this->getVariantFallback($v);
392 if(array_key_exists($vf, $carray))
393 $carray[$v] = $carray[$vf];
397 foreach($this->mVariants
as $vfrom) {
398 if(!array_key_exists($vfrom, $carray))
400 foreach($this->mVariants
as $vto) {
403 if(!array_key_exists($vto, $carray))
405 $this->mTables
[$vto][$carray[$vfrom]] = $carray[$vto];
409 if ( $this->mUseFss
) {
410 $this->generateFssObjects();
417 if(array_key_exists(1, $marked))
418 $text .= $this->autoConvert($marked[1]);
425 * parse the manually marked conversion rule
426 * @param string $rule the text of the rule
427 * @return array of the translation in each variant
430 function parseManualRule($rules, $flags=array()) {
432 $choice = explode($this->mMarkup
['varsep'], $rules);
434 if(sizeof($choice) == 1) {
435 /* a single choice */
436 foreach($this->mVariants
as $v)
437 $carray[$v] = $choice[0];
440 foreach($choice as $c) {
441 $v = explode($this->mMarkup
['codesep'], $c);
442 if(sizeof($v) != 2) // syntax error, skip
444 $carray[trim($v[0])] = trim($v[1]);
451 * if a language supports multiple variants, it is
452 * possible that non-existing link in one variant
453 * actually exists in another variant. this function
454 * tries to find it. See e.g. LanguageZh.php
456 * @param string $link the name of the link
457 * @param mixed $nt the title object of the link
458 * @return null the input parameters may be modified upon return
461 function findVariantLink( &$link, &$nt ) {
462 global $wgDisableLangConversion;
463 $pref = $this->getPreferredVariant();
466 $ns = $nt->getNamespace();
468 $variants = $this->autoConvertToAllVariants($link);
469 if($variants == false) //give up
471 foreach( $variants as $v ) {
472 $varnt = Title
::newFromText( $v, $ns );
473 if( $varnt && $varnt->getArticleID() > 0 ) {
475 if( !$wgDisableLangConversion )
483 * returns language specific hash options
487 function getExtraHashOptions() {
488 $variant = $this->getPreferredVariant();
489 return '!' . $variant ;
493 * get title text as defined in the body of the article text
497 function getParsedTitle() {
498 return $this->mTitleDisplay
;
502 * a write lock to the cache
506 function lockCache() {
509 for($i=0; $i<30; $i++
) {
510 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
522 function unlockCache() {
524 $wgMemc->delete($this->mCacheKey
. "lock");
529 * Load default conversion tables
530 * This method must be implemented in derived class
534 function loadDefaultTables() {
535 $name = get_class($this);
536 wfDie("Must implement loadDefaultTables() method in class $name");
540 * load conversion tables either from the cache or the disk
543 function loadTables($fromcache=true) {
545 if( $this->mTablesLoaded
)
547 $this->mTablesLoaded
= true;
549 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
550 if( !empty( $this->mTables
) ) //all done
553 // not in cache, or we need a fresh reload.
554 // we will first load the default tables
555 // then update them using things in MediaWiki:Zhconversiontable/*
556 global $wgMessageCache;
557 $this->loadDefaultTables();
558 foreach($this->mVariants
as $var) {
559 $cached = $this->parseCachedTable($var);
560 $this->mTables
[$var] = array_merge($this->mTables
[$var], $cached);
563 $this->postLoadTables();
565 if($this->lockCache()) {
566 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
567 $this->unlockCache();
569 if ( $this->mUseFss
) {
570 $this->generateFssObjects();
575 * Generate FSS objects. The FSS extension must be available.
577 function generateFssObjects() {
578 foreach ( $this->mTables
as $variant => $table ) {
579 $this->mFssObjects
[$variant] = fss_prep_replace( $table );
584 * Hook for post processig after conversion tables are loaded
587 function postLoadTables() {}
590 * Reload the conversion tables
594 function reloadTables() {
596 unset($this->mTables
);
597 $this->mTablesLoaded
= false;
598 $this->loadTables(false);
603 * parse the conversion table stored in the cache
605 * the tables should be in blocks of the following form:
613 * to make the tables more manageable, subpages are allowed
614 * and will be parsed recursively if $recursive=true
618 function parseCachedTable($code, $subpage='', $recursive=true) {
619 global $wgMessageCache;
620 static $parsed = array();
622 if(!is_object($wgMessageCache))
625 $key = 'Conversiontable/'.$code;
627 $key .= '/' . $subpage;
629 if(array_key_exists($key, $parsed))
633 $txt = $wgMessageCache->get( $key, true, true, true );
635 // get all subpage links of the form
636 // [[MediaWiki:conversiontable/zh-xx/...|...]]
637 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
638 $subs = explode('[[', $txt);
640 foreach( $subs as $sub ) {
641 $link = explode(']]', $sub, 2);
642 if(count($link) != 2)
644 $b = explode('|', $link[0]);
645 $b = explode('/', trim($b[0]), 3);
651 if($b[0] == $linkhead && $b[1] == $code) {
652 $sublinks[] = $sublink;
657 // parse the mappings in this page
658 $blocks = explode($this->mMarkup
['begin'], $txt);
659 array_shift($blocks);
661 foreach($blocks as $block) {
662 $mappings = explode($this->mMarkup
['end'], $block, 2);
663 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
664 $table = explode( ';', $stripped );
665 foreach( $table as $t ) {
666 $m = explode( '=>', $t );
667 if( count( $m ) != 2)
669 // trim any trailling comments starting with '//'
670 $tt = explode('//', $m[1], 2);
671 $ret[trim($m[0])] = trim($tt[0]);
674 $parsed[$key] = true;
677 // recursively parse the subpages
679 foreach($sublinks as $link) {
680 $s = $this->parseCachedTable($code, $link, $recursive);
681 $ret = array_merge($ret, $s);
685 if ($this->mUcfirst
) {
686 foreach ($ret as $k => $v) {
687 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
694 * Enclose a string with the "no conversion" tag. This is used by
695 * various functions in the Parser
697 * @param string $text text to be tagged for no conversion
698 * @return string the tagged text
700 function markNoConversion($text, $noParse=false) {
701 # don't mark if already marked
702 if(strpos($text, $this->mMarkup
['begin']) ||
703 strpos($text, $this->mMarkup
['end']))
706 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
711 * convert the sorting key for category links. this should make different
712 * keys that are variants of each other map to the same key
714 function convertCategoryKey( $key ) {
718 * hook to refresh the cache of conversion tables when
719 * MediaWiki:conversiontable* is updated
722 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
723 $titleobj = $article->getTitle();
724 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
726 global $wgContLang; // should be an LanguageZh.
727 if(get_class($wgContLang) != 'languagezh')
730 $title = $titleobj->getDBkey();
731 $t = explode('/', $title, 3);
733 if( $c > 1 && $t[0] == 'Conversiontable' ) {
734 if(in_array($t[1], $this->mVariants
)) {
735 $this->reloadTables();
742 function setNoTitleConvert(){
743 $this->mNoTitleConvert
= true;