ff7395105a68c3b5af19cc549ead070619cb59ce
3 Copyright (C) 2005 by Zhengzhu Feng (zhengzhu@gmail.com)
5 This file is distributed under the terms of GPL
11 * @subpackage Language
14 class LanguageConverter
{
15 var $mPreferredVariant='';
16 var $mMainLanguageCode;
17 var $mVariants, $mVariantFallbacks;
18 var $mTablesLoaded = false;
20 var $mTitleDisplay='';
21 var $mDoTitleConvert=true, $mDoContentConvert=true;
28 * @param string $maincode the main language code of this language
29 * @param array $variants the supported variants of this language
30 * @param array $variantfallback the fallback language of each variant
31 * @param array $markup array defining the markup used for manual conversion
34 function LanguageConverter($langobj, $maincode,
36 $variantfallbacks=array(),
37 $markup=array('begin'=>'-{',
42 $this->mLangObj
= $langobj;
43 $this->mMainLanguageCode
= $maincode;
44 $this->mVariants
= $variants;
45 $this->mVariantFallbacks
= $variantfallbacks;
46 $this->mCacheKey
= $wgDBname . ":conversiontables";
47 $this->mMarkup
= $markup;
53 function getVariants() {
54 return $this->mVariants
;
58 * in case some variant is not defined in the markup, we need
59 * to have some fallback. for example, in zh, normally people
60 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
61 * when zh-sg is preferred but not defined, we will pick zh-cn
62 * in this case. right now this is only used by zh.
64 * @param string $v the language code of the variant
65 * @return string the code of the fallback language or false if there is no fallback
68 function getVariantFallback($v) {
69 return $this->mVariantFallbacks
[$v];
74 * get preferred language variants.
75 * @return string the preferred language code
78 function getPreferredVariant() {
79 global $wgUser, $wgRequest;
81 if($this->mPreferredVariant
)
82 return $this->mPreferredVariant
;
84 // see if the preference is set in the request
85 $req = $wgRequest->getText( 'variant' );
86 if( in_array( $req, $this->mVariants
) ) {
87 $this->mPreferredVariant
= $req;
91 // get language variant preference from logged in users
92 if(is_object($wgUser) && $wgUser->isLoggedIn() ) {
93 $this->mPreferredVariant
= $wgUser->getOption('variant');
96 # FIXME rewrite code for parsing http header. The current code
97 # is written specific for detecting zh- variants
98 if( !$this->mPreferredVariant
) {
99 // see if some zh- variant is set in the http header,
100 $this->mPreferredVariant
=$this->mMainLanguageCode
;
101 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
102 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
103 $zh = strstr($header, 'zh-');
105 $this->mPreferredVariant
= substr($zh,0,5);
110 return $this->mPreferredVariant
;
114 * dictionary-based conversion
116 * @param string $text the text to be converted
117 * @param string $toVariant the target language code
118 * @return string the converted text
121 function autoConvert($text, $toVariant=false) {
122 $fname="LanguageConverter::autoConvert";
123 wfProfileIn( $fname );
125 if(!$this->mTablesLoaded
)
129 $toVariant = $this->getPreferredVariant();
130 if(!in_array($toVariant, $this->mVariants
))
135 $a = explode('<', $text);
136 $a0 = array_shift($a);
137 $ret .= strtr($a0, $this->mTables
[$toVariant]);
138 foreach( $a as $aa ) {
139 $b = explode('>', $aa, 2);
142 $ret .= '>' . strtr($b[1], $this->mTables
[$toVariant]);
145 # /* put back the marker if any */
147 # $reg = '<'.$reg.'>';
148 # $ret = preg_replace('/'.$reg.'/', '${1}', $ret);
151 wfProfileOut( $fname );
156 * convert text to all supported variants
158 * @param string $text the text to be converted
159 * @return array of string
162 function autoConvertToAllVariants($text) {
163 $fname="LanguageConverter::autoConvertToAllVariants";
164 wfProfileIn( $fname );
165 if( !$this->mTablesLoaded
)
169 foreach($this->mVariants
as $variant) {
170 $ret[$variant] = strtr($text, $this->mTables
[$variant]);
172 wfProfileOut( $fname );
177 * convert text to different variants of a language. the automatic
178 * conversion is done in autoConvert(). here we parse the text
179 * marked with -{}-, which specifies special conversions of the
180 * text that can not be accomplished in autoConvert()
182 * syntax of the markup:
183 * -{code1:text1;code2:text2;...}- or
184 * -{text}- in which case no conversion should take place for text
186 * @param string $text text to be converted
187 * @param bool $isTitle whether this conversion is for the article title
188 * @return string converted text
191 function convert( $text , $isTitle=false) {
192 global $wgDisableLangConversion;
193 if($wgDisableLangConversion)
196 $mw =& MagicWord
::get( MAG_NOTITLECONVERT
);
197 if( $mw->matchAndRemove( $text ) )
198 $this->mDoTitleConvert
= false;
200 $mw =& MagicWord
::get( MAG_NOCONTENTCONVERT
);
201 if( $mw->matchAndRemove( $text ) ) {
202 $this->mDoContentConvert
= false;
205 // no conversion if redirecting
206 $mw =& MagicWord
::get( MAG_REDIRECT
);
207 if( $mw->matchStart( $text ))
211 if( !$this->mDoTitleConvert
) {
212 $this->mTitleDisplay
= $text;
215 if( !empty($this->mTitleDisplay
))
216 return $this->mTitleDisplay
;
219 $isredir = $wgRequest->getText( 'redirect', 'yes' );
220 $action = $wgRequest->getText( 'action' );
221 if ( $isredir == 'no' ||
$action == 'edit' ) {
225 $this->mTitleDisplay
= $this->autoConvert($text);
226 return $this->mTitleDisplay
;
230 if( !$this->mDoContentConvert
)
233 $search = array('/('.UNIQ_PREFIX
.'-[a-zA-Z0-9]+)/', //nowiki marker
234 '/(&[a-z#][a-z0-9]+;)/', //html entities
236 $replace = $this->mMarkup
['begin'].'${1}'.$this->mMarkup
['end'];
238 $text = preg_replace($search, $replace, $text);
240 $plang = $this->getPreferredVariant();
241 $fallback = $this->mVariantFallbacks
[$plang];
242 $tarray = explode($this->mMarkup
['begin'], $text);
243 $tfirst = array_shift($tarray);
244 $text = $this->autoConvert($tfirst);
245 foreach($tarray as $txt) {
246 $marked = explode($this->mMarkup
['end'], $txt);
248 //strip since it interferes with the parsing, plus,
249 //all spaces should be stripped in this tag anyway.
250 $marked[0] = str_replace(' ', '', $marked[0]);
252 /* see if this conversion has special meaning
254 -{T|zh-cn:foo;zh-tw:bar}-
255 # convert all occurence of foo/bar in this article:
256 -{A|zh-cn:foo;zh-tw:bar}-
260 $tt = explode("|", $marked[0], 2);
261 if(sizeof($tt) == 2) {
262 $flag = trim($tt[0]);
263 $choice = explode(";", $tt[1]);
267 $choice = explode($this->mMarkup
['varsep'], $marked[0]);
271 if(!array_key_exists(1, $choice)) {
272 /* a single choice */
275 /* fill the carray if the conversion is for the whole article*/
277 foreach($this->mVariants
as $v) {
283 foreach($choice as $c) {
284 $v = explode($this->mMarkup
['codesep'], $c);
285 if(sizeof($v) != 2) // syntax error, skip
287 $carray[trim($v[0])] = trim($v[1]);
289 if(array_key_exists($plang, $carray))
290 $disp = $carray[$plang];
291 else if(array_key_exists($fallback, $carray))
292 $disp = $carray[$fallback];
294 if(empty($disp)) { // syntax error
298 if($flag == 'T') // for title only
299 $this->mTitleDisplay
= $disp;
303 /* modify the conversion table for this session*/
305 /* fill in the missing variants, if any,
307 foreach($this->mVariants
as $v) {
308 if(!array_key_exists($v, $carray)) {
309 $vf = $this->getVariantFallback($v);
310 if(array_key_exists($vf, $carray))
311 $carray[$v] = $carray[$vf];
314 foreach($this->mVariants
as $vfrom) {
315 if(!array_key_exists($vfrom, $carray))
317 foreach($this->mVariants
as $vto) {
320 if(!array_key_exists($vto, $carray))
322 $this->mTables
[$vto][$carray[$vfrom]] = $carray[$vto];
328 if(array_key_exists(1, $marked))
329 $text .= $this->autoConvert($marked[1]);
337 * if a language supports multiple variants, it is
338 * possible that non-existing link in one variant
339 * actually exists in another variant. this function
340 * tries to find it. See e.g. LanguageZh.php
342 * @param string $link the name of the link
343 * @param mixed $nt the title object of the link
344 * @return null the input parameters may be modified upon return
347 function findVariantLink( &$link, &$nt ) {
348 static $count=0; //used to limit this operation
349 static $cache=array();
350 global $wgDisableLangConversion;
351 $pref = $this->getPreferredVariant();
355 $variants = $this->autoConvertToAllVariants($link);
356 if($variants == false) //give up
358 foreach( $variants as $v ) {
359 if(isset($cache[$v]))
362 $varnt = Title
::newFromText( $v );
363 if( $varnt && $varnt->getArticleID() > 0 ) {
365 if( !$wgDisableLangConversion && $pref != 'zh' )
373 * returns language specific hash options
377 function getExtraHashOptions() {
378 $variant = $this->getPreferredVariant();
379 return '!' . $variant ;
383 * get title text as defined in the body of the article text
387 function getParsedTitle() {
388 return $this->mTitleDisplay
;
392 * a write lock to the cache
396 function lockCache() {
399 for($i=0; $i<30; $i++
) {
400 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
412 function unlockCache() {
414 $wgMemc->delete($this->mCacheKey
. "lock");
419 * Load default conversion tables
420 * This method must be implemented in derived class
424 function loadDefaultTables() {
425 $name = get_class($this);
426 die("Must implement loadDefaultTables() method in class $name");
430 * load conversion tables either from the cache or the disk
433 function loadTables($fromcache=true) {
435 if( $this->mTablesLoaded
)
437 $this->mTablesLoaded
= true;
439 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
440 if( !empty( $this->mTables
) ) //all done
443 // not in cache, or we need a fresh reload.
444 // we will first load the default tables
445 // then update them using things in MediaWiki:Zhconversiontable/*
446 global $wgMessageCache;
447 $this->loadDefaultTables();
448 foreach($this->mVariants
as $var) {
449 $cached = $this->parseCachedTable($var);
450 $this->mTables
[$var] = array_merge($this->mTables
[$var], $cached);
453 $this->postLoadTables();
455 if($this->lockCache()) {
456 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
457 $this->unlockCache();
462 * Hook for post processig after conversion tables are loaded
465 function postLoadTables() {}
468 function updateTablexxxx($code, $table) {
470 if(!$this->mTablesLoaded
)
473 $this->mTables
[$code] = array_merge($this->mTables
[$code], $table);
474 if($this->lockCache()) {
475 $wgMemc->delete($this->mCacheKey
);
476 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
477 $this->unlockCache();
482 * Reload the conversion tables
486 function reloadTables() {
488 unset($this->mTables
);
489 $this->mTablesLoaded
= false;
490 $this->loadTables(false);
495 * parse the conversion table stored in the cache
497 * the tables should be in blocks of the following form:
505 * to make the tables more manageable, subpages are allowed
506 * and will be parsed recursively if $recursive=true
510 function parseCachedTable($code, $subpage='', $recursive=true) {
511 global $wgMessageCache;
512 static $parsed = array();
514 if(!is_object($wgMessageCache))
517 $key = 'Conversiontable/'.$code;
519 $key .= '/' . $subpage;
521 if(array_key_exists($key, $parsed))
525 $txt = $wgMessageCache->get( $key, true, true, true );
527 // get all subpage links of the form
528 // [[MediaWiki:conversiontable/zh-xx/...|...]]
529 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
530 $subs = explode('[[', $txt);
532 foreach( $subs as $sub ) {
533 $link = explode(']]', $sub, 2);
534 if(count($link) != 2)
536 $b = explode('|', $link[0]);
537 $b = explode('/', trim($b[0]), 3);
543 if($b[0] == $linkhead && $b[1] == $code) {
544 $sublinks[] = $sublink;
549 // parse the mappings in this page
550 $blocks = explode('-{', $txt);
551 array_shift($blocks);
553 foreach($blocks as $block) {
554 $mappings = explode('}-', $block, 2);
555 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
556 $table = explode( ';', $stripped );
557 foreach( $table as $t ) {
558 $m = explode( '=>', $t );
559 if( count( $m ) != 2)
561 // trim any trailling comments starting with '//'
562 $tt = explode('//', $m[1], 2);
563 $ret[trim($m[0])] = trim($tt[0]);
566 $parsed[$key] = true;
569 // recursively parse the subpages
571 foreach($sublinks as $link) {
572 $s = $this->parseCachedTable($code, $link, $recursive);
573 $ret = array_merge($ret, $s);
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 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
591 * hook to refresh the cache of conversion tables when
592 * MediaWiki:conversiontable* is updated
595 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
596 $titleobj = $article->getTitle();
597 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
599 global $wgContLang; // should be an LanguageZh.
600 if(get_class($wgContLang) != 'languagezh')
603 $title = $titleobj->getDBkey();
604 $t = explode('/', $title, 3);
606 if( $c > 1 && $t[0] == 'Conversiontable' ) {
607 if(in_array($t[1], $this->mVariants
)) {
608 $this->reloadTables();