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 LanguageConverter($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 * @return string the preferred language code
79 function getPreferredVariant() {
80 global $wgUser, $wgRequest;
82 if($this->mPreferredVariant
)
83 return $this->mPreferredVariant
;
85 // see if the preference is set in the request
86 $req = $wgRequest->getText( 'variant' );
87 if( in_array( $req, $this->mVariants
) ) {
88 $this->mPreferredVariant
= $req;
92 // get language variant preference from logged in users
93 if(is_object($wgUser) && $wgUser->isLoggedIn() ) {
94 $this->mPreferredVariant
= $wgUser->getOption('variant');
97 # FIXME rewrite code for parsing http header. The current code
98 # is written specific for detecting zh- variants
99 if( !$this->mPreferredVariant
) {
100 // see if some zh- variant is set in the http header,
101 $this->mPreferredVariant
=$this->mMainLanguageCode
;
102 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
103 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
104 $zh = strstr($header, 'zh-');
106 $this->mPreferredVariant
= substr($zh,0,5);
111 return $this->mPreferredVariant
;
115 * dictionary-based conversion
117 * @param string $text the text to be converted
118 * @param string $toVariant the target language code
119 * @return string the converted text
122 function autoConvert($text, $toVariant=false) {
123 $fname="LanguageConverter::autoConvert";
125 wfProfileIn( $fname );
127 if(!$this->mTablesLoaded
)
131 $toVariant = $this->getPreferredVariant();
132 if(!in_array($toVariant, $this->mVariants
))
136 $reg = '/<[^>]+>|&[a-z#][a-z0-9]+;|'.UNIQ_PREFIX
.'-[a-zA-Z0-9]+/';
137 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
140 $m = array_shift($matches);
141 $ret = strtr($m[0], $this->mTables
[$toVariant]);
142 $mstart = $m[1]+
strlen($m[0]);
143 foreach($matches as $m) {
144 $ret .= substr($text, $mstart, $m[1]-$mstart);
145 $ret .= strtr($m[0], $this->mTables
[$toVariant]);
146 $mstart = $m[1] +
strlen($m[0]);
148 wfProfileOut( $fname );
153 * convert text to all supported variants
155 * @param string $text the text to be converted
156 * @return array of string
159 function autoConvertToAllVariants($text) {
160 $fname="LanguageConverter::autoConvertToAllVariants";
161 wfProfileIn( $fname );
162 if( !$this->mTablesLoaded
)
166 foreach($this->mVariants
as $variant) {
167 $ret[$variant] = strtr($text, $this->mTables
[$variant]);
169 wfProfileOut( $fname );
174 * convert text to different variants of a language. the automatic
175 * conversion is done in autoConvert(). here we parse the text
176 * marked with -{}-, which specifies special conversions of the
177 * text that can not be accomplished in autoConvert()
179 * syntax of the markup:
180 * -{code1:text1;code2:text2;...}- or
181 * -{text}- in which case no conversion should take place for text
183 * @param string $text text to be converted
184 * @param bool $isTitle whether this conversion is for the article title
185 * @return string converted text
188 function convert( $text , $isTitle=false) {
189 global $wgDisableLangConversion;
192 /* don't do anything if this is the conversion table */
193 if($wgTitle->getNamespace() == NS_MEDIAWIKI
&&
194 strpos($wgTitle->getText(), "Conversiontable")!==false)
197 if($wgDisableLangConversion)
200 $mw =& MagicWord
::get( MAG_NOTITLECONVERT
);
201 if( $mw->matchAndRemove( $text ) )
202 $this->mDoTitleConvert
= false;
204 $mw =& MagicWord
::get( MAG_NOCONTENTCONVERT
);
205 if( $mw->matchAndRemove( $text ) ) {
206 $this->mDoContentConvert
= false;
209 // no conversion if redirecting
210 $mw =& MagicWord
::get( MAG_REDIRECT
);
211 if( $mw->matchStart( $text ))
215 if( !$this->mDoTitleConvert
) {
216 $this->mTitleDisplay
= $text;
219 if( !empty($this->mTitleDisplay
))
220 return $this->mTitleDisplay
;
223 $isredir = $wgRequest->getText( 'redirect', 'yes' );
224 $action = $wgRequest->getText( 'action' );
225 if ( $isredir == 'no' ||
$action == 'edit' ) {
229 $this->mTitleDisplay
= $this->autoConvert($text);
230 return $this->mTitleDisplay
;
234 if( !$this->mDoContentConvert
)
237 $plang = $this->getPreferredVariant();
238 $fallback = $this->mVariantFallbacks
[$plang];
240 $tarray = explode($this->mMarkup
['begin'], $text);
241 $tfirst = array_shift($tarray);
242 $text = $this->autoConvert($tfirst);
243 foreach($tarray as $txt) {
244 $marked = explode($this->mMarkup
['end'], $txt);
246 $tt = explode($this->mMarkup
['flagsep'], $marked[0], 2);
248 if(sizeof($tt) == 2) {
249 $f = explode($this->mMarkup
['varsep'], $tt[0]);
252 if(array_key_exists($ff, $this->mFlags
) &&
253 !array_key_exists($this->mFlags
[$ff], $flags))
254 $flags[] = $this->mFlags
[$ff];
261 #FIXME: may cause trouble here...
262 //strip since it interferes with the parsing, plus,
263 //all spaces should be stripped in this tag anyway.
264 $rules = str_replace(' ', '', $rules);
266 $carray = $this->parseManualRule($rules, $flags);
268 if(array_key_exists($plang, $carray))
269 $disp = $carray[$plang];
270 else if(array_key_exists($fallback, $carray))
271 $disp = $carray[$fallback];
273 if(in_array('T', $flags))
274 $this->mTitleDisplay
= $disp;
278 if(in_array('A', $flags)) {
279 /* modify the conversion table for this session*/
281 /* fill in the missing variants, if any,
283 foreach($this->mVariants
as $v) {
284 if(!array_key_exists($v, $carray)) {
285 $vf = $this->getVariantFallback($v);
286 if(array_key_exists($vf, $carray))
287 $carray[$v] = $carray[$vf];
291 foreach($this->mVariants
as $vfrom) {
292 if(!array_key_exists($vfrom, $carray))
294 foreach($this->mVariants
as $vto) {
297 if(!array_key_exists($vto, $carray))
299 $this->mTables
[$vto][$carray[$vfrom]] = $carray[$vto];
308 if(array_key_exists(1, $marked))
309 $text .= $this->autoConvert($marked[1]);
316 * parse the manually marked conversion rule
317 * @param string $rule the text of the rule
318 * @return array of the translation in each variant
321 function parseManualRule($rules, $flags=array()) {
323 $choice = explode($this->mMarkup
['varsep'], $rules);
325 if(sizeof($choice) == 1) {
326 /* a single choice */
327 foreach($this->mVariants
as $v)
328 $carray[$v] = $choice[0];
331 foreach($choice as $c) {
332 $v = explode($this->mMarkup
['codesep'], $c);
333 if(sizeof($v) != 2) // syntax error, skip
335 $carray[trim($v[0])] = trim($v[1]);
342 * if a language supports multiple variants, it is
343 * possible that non-existing link in one variant
344 * actually exists in another variant. this function
345 * tries to find it. See e.g. LanguageZh.php
347 * @param string $link the name of the link
348 * @param mixed $nt the title object of the link
349 * @return null the input parameters may be modified upon return
352 function findVariantLink( &$link, &$nt ) {
353 static $count=0; //used to limit this operation
354 static $cache=array();
355 global $wgDisableLangConversion;
356 $pref = $this->getPreferredVariant();
359 $ns = $nt->getNamespace();
360 if( $count > 50 && $ns != NS_CATEGORY
)
363 $variants = $this->autoConvertToAllVariants($link);
364 if($variants == false) //give up
366 foreach( $variants as $v ) {
367 if(isset($cache[$v]))
370 $varnt = Title
::newFromText( $v );
371 if( $varnt && $varnt->getArticleID() > 0 ) {
373 if( !$wgDisableLangConversion )
381 * returns language specific hash options
385 function getExtraHashOptions() {
386 $variant = $this->getPreferredVariant();
387 return '!' . $variant ;
391 * get title text as defined in the body of the article text
395 function getParsedTitle() {
396 return $this->mTitleDisplay
;
400 * a write lock to the cache
404 function lockCache() {
407 for($i=0; $i<30; $i++
) {
408 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
420 function unlockCache() {
422 $wgMemc->delete($this->mCacheKey
. "lock");
427 * Load default conversion tables
428 * This method must be implemented in derived class
432 function loadDefaultTables() {
433 $name = get_class($this);
434 die("Must implement loadDefaultTables() method in class $name");
438 * load conversion tables either from the cache or the disk
441 function loadTables($fromcache=true) {
443 if( $this->mTablesLoaded
)
445 $this->mTablesLoaded
= true;
447 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
448 if( !empty( $this->mTables
) ) //all done
451 // not in cache, or we need a fresh reload.
452 // we will first load the default tables
453 // then update them using things in MediaWiki:Zhconversiontable/*
454 global $wgMessageCache;
455 $this->loadDefaultTables();
456 foreach($this->mVariants
as $var) {
457 $cached = $this->parseCachedTable($var);
458 $this->mTables
[$var] = array_merge($this->mTables
[$var], $cached);
461 $this->postLoadTables();
463 if($this->lockCache()) {
464 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
465 $this->unlockCache();
470 * Hook for post processig after conversion tables are loaded
473 function postLoadTables() {}
476 * Reload the conversion tables
480 function reloadTables() {
482 unset($this->mTables
);
483 $this->mTablesLoaded
= false;
484 $this->loadTables(false);
489 * parse the conversion table stored in the cache
491 * the tables should be in blocks of the following form:
499 * to make the tables more manageable, subpages are allowed
500 * and will be parsed recursively if $recursive=true
504 function parseCachedTable($code, $subpage='', $recursive=true) {
505 global $wgMessageCache;
506 static $parsed = array();
508 if(!is_object($wgMessageCache))
511 $key = 'Conversiontable/'.$code;
513 $key .= '/' . $subpage;
515 if(array_key_exists($key, $parsed))
519 $txt = $wgMessageCache->get( $key, true, true, true );
521 // get all subpage links of the form
522 // [[MediaWiki:conversiontable/zh-xx/...|...]]
523 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
524 $subs = explode('[[', $txt);
526 foreach( $subs as $sub ) {
527 $link = explode(']]', $sub, 2);
528 if(count($link) != 2)
530 $b = explode('|', $link[0]);
531 $b = explode('/', trim($b[0]), 3);
537 if($b[0] == $linkhead && $b[1] == $code) {
538 $sublinks[] = $sublink;
543 // parse the mappings in this page
544 $blocks = explode($this->mMarkup
['begin'], $txt);
545 array_shift($blocks);
547 foreach($blocks as $block) {
548 $mappings = explode($this->mMarkup
['end'], $block, 2);
549 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
550 $table = explode( ';', $stripped );
551 foreach( $table as $t ) {
552 $m = explode( '=>', $t );
553 if( count( $m ) != 2)
555 // trim any trailling comments starting with '//'
556 $tt = explode('//', $m[1], 2);
557 $ret[trim($m[0])] = trim($tt[0]);
560 $parsed[$key] = true;
563 // recursively parse the subpages
565 foreach($sublinks as $link) {
566 $s = $this->parseCachedTable($code, $link, $recursive);
567 $ret = array_merge($ret, $s);
571 if ($this->mUcfirst
) {
572 foreach ($ret as $k => $v) {
573 $ret[LanguageUtf8
::ucfirst($k)] = LanguageUtf8
::ucfirst($v);
580 * Enclose a string with the "no conversion" tag. This is used by
581 * various functions in the Parser
583 * @param string $text text to be tagged for no conversion
584 * @return string the tagged text
586 function markNoConversion($text) {
587 # don't mark if already marked
588 if(strpos($text, $this->mMarkup
['begin']) ||
589 strpos($text, $this->mMarkup
['end']))
592 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
597 * convert the sorting key for category links. this should make different
598 * keys that are variants of each other map to the same key
600 function convertCategoryKey( $key ) {
604 * hook to refresh the cache of conversion tables when
605 * MediaWiki:conversiontable* is updated
608 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
609 $titleobj = $article->getTitle();
610 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
612 global $wgContLang; // should be an LanguageZh.
613 if(get_class($wgContLang) != 'languagezh')
616 $title = $titleobj->getDBkey();
617 $t = explode('/', $title, 3);
619 if( $c > 1 && $t[0] == 'Conversiontable' ) {
620 if(in_array($t[1], $this->mVariants
)) {
621 $this->reloadTables();