Updates and polishing
[mediawiki.git] / languages / LanguageConverter.php
blob38cb3dcb4e83495599fc165843553220dc9b2d3f
1 <?php
2 /**
3 * @package MediaWiki
4 * @subpackage Language
6 * @author Zhengzhu Feng <zhengzhu@gmail.com>
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
8 */
10 class LanguageConverter {
11 var $mPreferredVariant='';
12 var $mMainLanguageCode;
13 var $mVariants, $mVariantFallbacks;
14 var $mTablesLoaded = false;
15 var $mTables;
16 var $mTitleDisplay='';
17 var $mDoTitleConvert=true, $mDoContentConvert=true;
18 var $mCacheKey;
19 var $mLangObj;
20 var $mMarkup;
21 var $mFlags;
22 var $mUcfirst = false;
23 /**
24 * Constructor
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
31 * @access public
33 function LanguageConverter($langobj, $maincode,
34 $variants=array(),
35 $variantfallbacks=array(),
36 $markup=array(),
37 $flags = array()) {
38 global $wgDBname;
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);
51 /**
52 * @access public
54 function getVariants() {
55 return $this->mVariants;
58 /**
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
67 * @access private
69 function getVariantFallback($v) {
70 return $this->mVariantFallbacks[$v];
74 /**
75 * get preferred language variants.
76 * @return string the preferred language code
77 * @access public
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;
89 return $req;
92 // get language variant preference from logged in users
93 if(is_object($wgUser) && $wgUser->isLoggedIn() ) {
94 $this->mPreferredVariant = $wgUser->getOption('variant');
95 return $this->mPreferredVariant;
98 # FIXME rewrite code for parsing http header. The current code
99 # is written specific for detecting zh- variants
100 if( !$this->mPreferredVariant ) {
101 // see if some supported language variant is set in the
102 // http header, but we don't set the mPreferredVariant
103 // variable in case this is called before the user's
104 // preference is loaded
105 $pv=$this->mMainLanguageCode;
106 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
107 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
108 $zh = strstr($header, 'zh-');
109 if($zh) {
110 $pv = substr($zh,0,5);
113 return $pv;
118 * dictionary-based conversion
120 * @param string $text the text to be converted
121 * @param string $toVariant the target language code
122 * @return string the converted text
123 * @access private
125 function autoConvert($text, $toVariant=false) {
126 $fname="LanguageConverter::autoConvert";
128 wfProfileIn( $fname );
130 if(!$this->mTablesLoaded)
131 $this->loadTables();
133 if(!$toVariant)
134 $toVariant = $this->getPreferredVariant();
135 if(!in_array($toVariant, $this->mVariants))
136 return $text;
138 /* we convert everything except:
139 1. html markups (anything between < and >)
140 2. html entities
141 3. place holders created by the parser
143 global $wgParser;
144 if (isset($wgParser))
145 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
146 else
147 $marker = "";
148 $reg = '/<[^>]+>|&[a-z#][a-z0-9]+;' . $marker . '/';
149 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
152 $m = array_shift($matches);
153 $ret = strtr($m[0], $this->mTables[$toVariant]);
154 $mstart = $m[1]+strlen($m[0]);
155 foreach($matches as $m) {
156 $ret .= substr($text, $mstart, $m[1]-$mstart);
157 $ret .= strtr($m[0], $this->mTables[$toVariant]);
158 $mstart = $m[1] + strlen($m[0]);
160 wfProfileOut( $fname );
161 return $ret;
165 * convert text to all supported variants
167 * @param string $text the text to be converted
168 * @return array of string
169 * @access private
171 function autoConvertToAllVariants($text) {
172 $fname="LanguageConverter::autoConvertToAllVariants";
173 wfProfileIn( $fname );
174 if( !$this->mTablesLoaded )
175 $this->loadTables();
177 $ret = array();
178 foreach($this->mVariants as $variant) {
179 $ret[$variant] = strtr($text, $this->mTables[$variant]);
181 wfProfileOut( $fname );
182 return $ret;
186 * Convert text using a parser object for context
188 function parserConvert( $text, &$parser ) {
189 global $wgDisableLangConversion;
190 /* don't do anything if this is the conversion table */
191 if ( $parser->mTitle->getNamespace() == NS_MEDIAWIKI &&
192 strpos($parser->mTitle->getText, "Conversiontable") !== false )
194 return $text;
197 if($wgDisableLangConversion)
198 return $text;
200 $text = $this->convert( $text );
201 $parser->mOutput->setTitleText( $this->mTitleDisplay );
202 return $text;
206 * convert text to different variants of a language. the automatic
207 * conversion is done in autoConvert(). here we parse the text
208 * marked with -{}-, which specifies special conversions of the
209 * text that can not be accomplished in autoConvert()
211 * syntax of the markup:
212 * -{code1:text1;code2:text2;...}- or
213 * -{text}- in which case no conversion should take place for text
215 * @param string $text text to be converted
216 * @param bool $isTitle whether this conversion is for the article title
217 * @return string converted text
218 * @access public
220 function convert( $text , $isTitle=false) {
221 $mw =& MagicWord::get( MAG_NOTITLECONVERT );
222 if( $mw->matchAndRemove( $text ) )
223 $this->mDoTitleConvert = false;
225 $mw =& MagicWord::get( MAG_NOCONTENTCONVERT );
226 if( $mw->matchAndRemove( $text ) ) {
227 $this->mDoContentConvert = false;
230 // no conversion if redirecting
231 $mw =& MagicWord::get( MAG_REDIRECT );
232 if( $mw->matchStart( $text ))
233 return $text;
235 if( $isTitle ) {
236 if( !$this->mDoTitleConvert ) {
237 $this->mTitleDisplay = $text;
238 return $text;
240 if( !empty($this->mTitleDisplay))
241 return $this->mTitleDisplay;
243 global $wgRequest;
244 $isredir = $wgRequest->getText( 'redirect', 'yes' );
245 $action = $wgRequest->getText( 'action' );
246 if ( $isredir == 'no' || $action == 'edit' ) {
247 return $text;
249 else {
250 $this->mTitleDisplay = $this->autoConvert($text);
251 return $this->mTitleDisplay;
255 if( !$this->mDoContentConvert )
256 return $text;
258 $plang = $this->getPreferredVariant();
259 $fallback = $this->mVariantFallbacks[$plang];
261 $tarray = explode($this->mMarkup['begin'], $text);
262 $tfirst = array_shift($tarray);
263 $text = $this->autoConvert($tfirst);
264 foreach($tarray as $txt) {
265 $marked = explode($this->mMarkup['end'], $txt);
266 $flags = array();
267 $tt = explode($this->mMarkup['flagsep'], $marked[0], 2);
269 if(sizeof($tt) == 2) {
270 $f = explode($this->mMarkup['varsep'], $tt[0]);
271 foreach($f as $ff) {
272 $ff = trim($ff);
273 if(array_key_exists($ff, $this->mFlags) &&
274 !array_key_exists($this->mFlags[$ff], $flags))
275 $flags[] = $this->mFlags[$ff];
277 $rules = $tt[1];
279 else
280 $rules = $marked[0];
282 #FIXME: may cause trouble here...
283 //strip &nbsp; since it interferes with the parsing, plus,
284 //all spaces should be stripped in this tag anyway.
285 $rules = str_replace('&nbsp;', '', $rules);
287 $carray = $this->parseManualRule($rules, $flags);
288 $disp = '';
289 if(array_key_exists($plang, $carray))
290 $disp = $carray[$plang];
291 else if(array_key_exists($fallback, $carray))
292 $disp = $carray[$fallback];
293 if($disp) {
294 if(in_array('T', $flags))
295 $this->mTitleDisplay = $disp;
296 else
297 $text .= $disp;
299 if(in_array('A', $flags)) {
300 /* modify the conversion table for this session*/
302 /* fill in the missing variants, if any,
303 with fallbacks */
304 foreach($this->mVariants as $v) {
305 if(!array_key_exists($v, $carray)) {
306 $vf = $this->getVariantFallback($v);
307 if(array_key_exists($vf, $carray))
308 $carray[$v] = $carray[$vf];
312 foreach($this->mVariants as $vfrom) {
313 if(!array_key_exists($vfrom, $carray))
314 continue;
315 foreach($this->mVariants as $vto) {
316 if($vfrom == $vto)
317 continue;
318 if(!array_key_exists($vto, $carray))
319 continue;
320 $this->mTables[$vto][$carray[$vfrom]] = $carray[$vto];
326 else {
327 $text .= $marked[0];
329 if(array_key_exists(1, $marked))
330 $text .= $this->autoConvert($marked[1]);
333 return $text;
337 * parse the manually marked conversion rule
338 * @param string $rule the text of the rule
339 * @return array of the translation in each variant
340 * @access private
342 function parseManualRule($rules, $flags=array()) {
344 $choice = explode($this->mMarkup['varsep'], $rules);
345 $carray = array();
346 if(sizeof($choice) == 1) {
347 /* a single choice */
348 foreach($this->mVariants as $v)
349 $carray[$v] = $choice[0];
351 else {
352 foreach($choice as $c) {
353 $v = explode($this->mMarkup['codesep'], $c);
354 if(sizeof($v) != 2) // syntax error, skip
355 continue;
356 $carray[trim($v[0])] = trim($v[1]);
359 return $carray;
363 * if a language supports multiple variants, it is
364 * possible that non-existing link in one variant
365 * actually exists in another variant. this function
366 * tries to find it. See e.g. LanguageZh.php
368 * @param string $link the name of the link
369 * @param mixed $nt the title object of the link
370 * @return null the input parameters may be modified upon return
371 * @access public
373 function findVariantLink( &$link, &$nt ) {
374 static $count=0; //used to limit this operation
375 static $cache=array();
376 global $wgDisableLangConversion;
377 $pref = $this->getPreferredVariant();
378 $ns=0;
379 if(is_object($nt))
380 $ns = $nt->getNamespace();
381 if( $count > 50 && $ns != NS_CATEGORY )
382 return;
383 $count++;
384 $variants = $this->autoConvertToAllVariants($link);
385 if($variants == false) //give up
386 return;
387 foreach( $variants as $v ) {
388 if(isset($cache[$v]))
389 continue;
390 $cache[$v] = 1;
391 $varnt = Title::newFromText( $v );
392 if( $varnt && $varnt->getArticleID() > 0 ) {
393 $nt = $varnt;
394 if( !$wgDisableLangConversion )
395 $link = $v;
396 break;
402 * returns language specific hash options
404 * @access public
406 function getExtraHashOptions() {
407 $variant = $this->getPreferredVariant();
408 return '!' . $variant ;
412 * get title text as defined in the body of the article text
414 * @access public
416 function getParsedTitle() {
417 return $this->mTitleDisplay;
421 * a write lock to the cache
423 * @access private
425 function lockCache() {
426 global $wgMemc;
427 $success = false;
428 for($i=0; $i<30; $i++) {
429 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
430 break;
431 sleep(1);
433 return $success;
437 * unlock cache
439 * @access private
441 function unlockCache() {
442 global $wgMemc;
443 $wgMemc->delete($this->mCacheKey . "lock");
448 * Load default conversion tables
449 * This method must be implemented in derived class
451 * @access private
453 function loadDefaultTables() {
454 $name = get_class($this);
455 wfDie("Must implement loadDefaultTables() method in class $name");
459 * load conversion tables either from the cache or the disk
460 * @access private
462 function loadTables($fromcache=true) {
463 global $wgMemc;
464 if( $this->mTablesLoaded )
465 return;
466 $this->mTablesLoaded = true;
467 if($fromcache) {
468 $this->mTables = $wgMemc->get( $this->mCacheKey );
469 if( !empty( $this->mTables ) ) //all done
470 return;
472 // not in cache, or we need a fresh reload.
473 // we will first load the default tables
474 // then update them using things in MediaWiki:Zhconversiontable/*
475 global $wgMessageCache;
476 $this->loadDefaultTables();
477 foreach($this->mVariants as $var) {
478 $cached = $this->parseCachedTable($var);
479 $this->mTables[$var] = array_merge($this->mTables[$var], $cached);
482 $this->postLoadTables();
484 if($this->lockCache()) {
485 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
486 $this->unlockCache();
491 * Hook for post processig after conversion tables are loaded
494 function postLoadTables() {}
497 * Reload the conversion tables
499 * @access private
501 function reloadTables() {
502 if($this->mTables)
503 unset($this->mTables);
504 $this->mTablesLoaded = false;
505 $this->loadTables(false);
510 * parse the conversion table stored in the cache
512 * the tables should be in blocks of the following form:
514 * -{
515 * word => word ;
516 * word => word ;
517 * ...
518 * }-
520 * to make the tables more manageable, subpages are allowed
521 * and will be parsed recursively if $recursive=true
523 * @access private
525 function parseCachedTable($code, $subpage='', $recursive=true) {
526 global $wgMessageCache;
527 static $parsed = array();
529 if(!is_object($wgMessageCache))
530 return array();
532 $key = 'Conversiontable/'.$code;
533 if($subpage)
534 $key .= '/' . $subpage;
536 if(array_key_exists($key, $parsed))
537 return array();
540 $txt = $wgMessageCache->get( $key, true, true, true );
542 // get all subpage links of the form
543 // [[MediaWiki:conversiontable/zh-xx/...|...]]
544 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
545 $subs = explode('[[', $txt);
546 $sublinks = array();
547 foreach( $subs as $sub ) {
548 $link = explode(']]', $sub, 2);
549 if(count($link) != 2)
550 continue;
551 $b = explode('|', $link[0]);
552 $b = explode('/', trim($b[0]), 3);
553 if(count($b)==3)
554 $sublink = $b[2];
555 else
556 $sublink = '';
558 if($b[0] == $linkhead && $b[1] == $code) {
559 $sublinks[] = $sublink;
564 // parse the mappings in this page
565 $blocks = explode($this->mMarkup['begin'], $txt);
566 array_shift($blocks);
567 $ret = array();
568 foreach($blocks as $block) {
569 $mappings = explode($this->mMarkup['end'], $block, 2);
570 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
571 $table = explode( ';', $stripped );
572 foreach( $table as $t ) {
573 $m = explode( '=>', $t );
574 if( count( $m ) != 2)
575 continue;
576 // trim any trailling comments starting with '//'
577 $tt = explode('//', $m[1], 2);
578 $ret[trim($m[0])] = trim($tt[0]);
581 $parsed[$key] = true;
584 // recursively parse the subpages
585 if($recursive) {
586 foreach($sublinks as $link) {
587 $s = $this->parseCachedTable($code, $link, $recursive);
588 $ret = array_merge($ret, $s);
592 if ($this->mUcfirst) {
593 foreach ($ret as $k => $v) {
594 $ret[LanguageUtf8::ucfirst($k)] = LanguageUtf8::ucfirst($v);
597 return $ret;
601 * Enclose a string with the "no conversion" tag. This is used by
602 * various functions in the Parser
604 * @param string $text text to be tagged for no conversion
605 * @return string the tagged text
607 function markNoConversion($text) {
608 # don't mark if already marked
609 if(strpos($text, $this->mMarkup['begin']) ||
610 strpos($text, $this->mMarkup['end']))
611 return $text;
613 $ret = $this->mMarkup['begin'] . $text . $this->mMarkup['end'];
614 return $ret;
618 * convert the sorting key for category links. this should make different
619 * keys that are variants of each other map to the same key
621 function convertCategoryKey( $key ) {
622 return $key;
625 * hook to refresh the cache of conversion tables when
626 * MediaWiki:conversiontable* is updated
627 * @access private
629 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
630 $titleobj = $article->getTitle();
631 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
633 global $wgContLang; // should be an LanguageZh.
634 if(get_class($wgContLang) != 'languagezh')
635 return true;
637 $title = $titleobj->getDBkey();
638 $t = explode('/', $title, 3);
639 $c = count($t);
640 if( $c > 1 && $t[0] == 'Conversiontable' ) {
641 if(in_array($t[1], $this->mVariants)) {
642 $this->reloadTables();
646 return true;