Merged localisation-work branch:
[lhc/web/wiklou.git] / languages / LanguageConverter.php
1 <?php
2 /**
3 * @package MediaWiki
4 * @subpackage Language
5 *
6 * @author Zhengzhu Feng <zhengzhu@gmail.com>
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
8 */
9
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
25 *
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
32 */
33 function __construct($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);
49 }
50
51 /**
52 * @access public
53 */
54 function getVariants() {
55 return $this->mVariants;
56 }
57
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.
64 *
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 * @private
68 */
69 function getVariantFallback($v) {
70 return $this->mVariantFallbacks[$v];
71 }
72
73
74 /**
75 * get preferred language variants.
76 * @param boolean $fromUser Get it from $wgUser's preferences
77 * @return string the preferred language code
78 * @access public
79 */
80 function getPreferredVariant( $fromUser = true ) {
81 global $wgUser, $wgRequest;
82
83 if($this->mPreferredVariant)
84 return $this->mPreferredVariant;
85
86 // see if the preference is set in the request
87 $req = $wgRequest->getText( 'variant' );
88 if( in_array( $req, $this->mVariants ) ) {
89 $this->mPreferredVariant = $req;
90 return $req;
91 }
92
93 // get language variant preference from logged in users
94 // Don't call this on stub objects because that causes infinite
95 // recursion during initialisation
96 if( $fromUser && $wgUser->isLoggedIn() ) {
97 $this->mPreferredVariant = $wgUser->getOption('variant');
98 return $this->mPreferredVariant;
99 }
100
101 # FIXME rewrite code for parsing http header. The current code
102 # is written specific for detecting zh- variants
103 if( !$this->mPreferredVariant ) {
104 // see if some supported language variant is set in the
105 // http header, but we don't set the mPreferredVariant
106 // variable in case this is called before the user's
107 // preference is loaded
108 $pv=$this->mMainLanguageCode;
109 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
110 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
111 $zh = strstr($header, 'zh-');
112 if($zh) {
113 $pv = substr($zh,0,5);
114 }
115 }
116 return $pv;
117 }
118 }
119
120 /**
121 * dictionary-based conversion
122 *
123 * @param string $text the text to be converted
124 * @param string $toVariant the target language code
125 * @return string the converted text
126 * @private
127 */
128 function autoConvert($text, $toVariant=false) {
129 $fname="LanguageConverter::autoConvert";
130
131 wfProfileIn( $fname );
132
133 if(!$this->mTablesLoaded)
134 $this->loadTables();
135
136 if(!$toVariant)
137 $toVariant = $this->getPreferredVariant();
138 if(!in_array($toVariant, $this->mVariants))
139 return $text;
140
141 /* we convert everything except:
142 1. html markups (anything between < and >)
143 2. html entities
144 3. place holders created by the parser
145 */
146 global $wgParser;
147 if (isset($wgParser))
148 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
149 else
150 $marker = "";
151
152 // this one is needed when the text is inside an html markup
153 $htmlfix = '|<[^>]+=\"[^(>=)]*$|^[^(<>=\")]*\"[^>]*>';
154
155 $reg = '/<[^>]+>|&[a-z#][a-z0-9]+;' . $marker . $htmlfix . '/';
156
157 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
158
159
160 $m = array_shift($matches);
161 $ret = strtr($m[0], $this->mTables[$toVariant]);
162 $mstart = $m[1]+strlen($m[0]);
163 foreach($matches as $m) {
164 $ret .= substr($text, $mstart, $m[1]-$mstart);
165 $ret .= strtr($m[0], $this->mTables[$toVariant]);
166 $mstart = $m[1] + strlen($m[0]);
167 }
168 wfProfileOut( $fname );
169 return $ret;
170 }
171
172 /**
173 * convert text to all supported variants
174 *
175 * @param string $text the text to be converted
176 * @return array of string
177 * @private
178 */
179 function autoConvertToAllVariants($text) {
180 $fname="LanguageConverter::autoConvertToAllVariants";
181 wfProfileIn( $fname );
182 if( !$this->mTablesLoaded )
183 $this->loadTables();
184
185 $ret = array();
186 foreach($this->mVariants as $variant) {
187 $ret[$variant] = strtr($text, $this->mTables[$variant]);
188 }
189 wfProfileOut( $fname );
190 return $ret;
191 }
192
193 /**
194 * Convert text using a parser object for context
195 */
196 function parserConvert( $text, &$parser ) {
197 global $wgDisableLangConversion;
198 /* don't do anything if this is the conversion table */
199 if ( $parser->mTitle->getNamespace() == NS_MEDIAWIKI &&
200 strpos($parser->mTitle->getText, "Conversiontable") !== false )
201 {
202 return $text;
203 }
204
205 if($wgDisableLangConversion)
206 return $text;
207
208 $text = $this->convert( $text );
209 $parser->mOutput->setTitleText( $this->mTitleDisplay );
210 return $text;
211 }
212
213 /**
214 * convert text to different variants of a language. the automatic
215 * conversion is done in autoConvert(). here we parse the text
216 * marked with -{}-, which specifies special conversions of the
217 * text that can not be accomplished in autoConvert()
218 *
219 * syntax of the markup:
220 * -{code1:text1;code2:text2;...}- or
221 * -{text}- in which case no conversion should take place for text
222 *
223 * @param string $text text to be converted
224 * @param bool $isTitle whether this conversion is for the article title
225 * @return string converted text
226 * @access public
227 */
228 function convert( $text , $isTitle=false) {
229 $mw =& MagicWord::get( 'notitleconvert' );
230 if( $mw->matchAndRemove( $text ) )
231 $this->mDoTitleConvert = false;
232
233 $mw =& MagicWord::get( 'nocontentconvert' );
234 if( $mw->matchAndRemove( $text ) ) {
235 $this->mDoContentConvert = false;
236 }
237
238 // no conversion if redirecting
239 $mw =& MagicWord::get( 'redirect' );
240 if( $mw->matchStart( $text ))
241 return $text;
242
243 if( $isTitle ) {
244 if( !$this->mDoTitleConvert ) {
245 $this->mTitleDisplay = $text;
246 return $text;
247 }
248 if( !empty($this->mTitleDisplay))
249 return $this->mTitleDisplay;
250
251 global $wgRequest;
252 $isredir = $wgRequest->getText( 'redirect', 'yes' );
253 $action = $wgRequest->getText( 'action' );
254 if ( $isredir == 'no' || $action == 'edit' ) {
255 return $text;
256 }
257 else {
258 $this->mTitleDisplay = $this->autoConvert($text);
259 return $this->mTitleDisplay;
260 }
261 }
262
263 if( !$this->mDoContentConvert )
264 return $text;
265
266 $plang = $this->getPreferredVariant();
267 if( isset( $this->mVariantFallbacks[$plang] ) ) {
268 $fallback = $this->mVariantFallbacks[$plang];
269 } else {
270 // This sounds... bad?
271 $fallback = '';
272 }
273
274 $tarray = explode($this->mMarkup['begin'], $text);
275 $tfirst = array_shift($tarray);
276 $text = $this->autoConvert($tfirst);
277 foreach($tarray as $txt) {
278 $marked = explode($this->mMarkup['end'], $txt, 2);
279 $flags = array();
280 $tt = explode($this->mMarkup['flagsep'], $marked[0], 2);
281
282 if(sizeof($tt) == 2) {
283 $f = explode($this->mMarkup['varsep'], $tt[0]);
284 foreach($f as $ff) {
285 $ff = trim($ff);
286 if(array_key_exists($ff, $this->mFlags) &&
287 !array_key_exists($this->mFlags[$ff], $flags))
288 $flags[] = $this->mFlags[$ff];
289 }
290 $rules = $tt[1];
291 }
292 else
293 $rules = $marked[0];
294
295 #FIXME: may cause trouble here...
296 //strip &nbsp; since it interferes with the parsing, plus,
297 //all spaces should be stripped in this tag anyway.
298 $rules = str_replace('&nbsp;', '', $rules);
299
300 $carray = $this->parseManualRule($rules, $flags);
301 $disp = '';
302 if(array_key_exists($plang, $carray))
303 $disp = $carray[$plang];
304 else if(array_key_exists($fallback, $carray))
305 $disp = $carray[$fallback];
306 if($disp) {
307 if(in_array('T', $flags))
308 $this->mTitleDisplay = $disp;
309 else
310 $text .= $disp;
311
312 if(in_array('A', $flags)) {
313 /* modify the conversion table for this session*/
314
315 /* fill in the missing variants, if any,
316 with fallbacks */
317 foreach($this->mVariants as $v) {
318 if(!array_key_exists($v, $carray)) {
319 $vf = $this->getVariantFallback($v);
320 if(array_key_exists($vf, $carray))
321 $carray[$v] = $carray[$vf];
322 }
323 }
324
325 foreach($this->mVariants as $vfrom) {
326 if(!array_key_exists($vfrom, $carray))
327 continue;
328 foreach($this->mVariants as $vto) {
329 if($vfrom == $vto)
330 continue;
331 if(!array_key_exists($vto, $carray))
332 continue;
333 $this->mTables[$vto][$carray[$vfrom]] = $carray[$vto];
334
335 }
336 }
337 }
338 }
339 else {
340 $text .= $marked[0];
341 }
342 if(array_key_exists(1, $marked))
343 $text .= $this->autoConvert($marked[1]);
344 }
345
346 return $text;
347 }
348
349 /**
350 * parse the manually marked conversion rule
351 * @param string $rule the text of the rule
352 * @return array of the translation in each variant
353 * @private
354 */
355 function parseManualRule($rules, $flags=array()) {
356
357 $choice = explode($this->mMarkup['varsep'], $rules);
358 $carray = array();
359 if(sizeof($choice) == 1) {
360 /* a single choice */
361 foreach($this->mVariants as $v)
362 $carray[$v] = $choice[0];
363 }
364 else {
365 foreach($choice as $c) {
366 $v = explode($this->mMarkup['codesep'], $c);
367 if(sizeof($v) != 2) // syntax error, skip
368 continue;
369 $carray[trim($v[0])] = trim($v[1]);
370 }
371 }
372 return $carray;
373 }
374
375 /**
376 * if a language supports multiple variants, it is
377 * possible that non-existing link in one variant
378 * actually exists in another variant. this function
379 * tries to find it. See e.g. LanguageZh.php
380 *
381 * @param string $link the name of the link
382 * @param mixed $nt the title object of the link
383 * @return null the input parameters may be modified upon return
384 * @access public
385 */
386 function findVariantLink( &$link, &$nt ) {
387 static $count=0; //used to limit this operation
388 static $cache=array();
389 global $wgDisableLangConversion;
390 $pref = $this->getPreferredVariant();
391 $ns=0;
392 if(is_object($nt))
393 $ns = $nt->getNamespace();
394 if( $count > 50 && $ns != NS_CATEGORY )
395 return;
396 $count++;
397 $variants = $this->autoConvertToAllVariants($link);
398 if($variants == false) //give up
399 return;
400 foreach( $variants as $v ) {
401 if(isset($cache[$v]))
402 continue;
403 $cache[$v] = 1;
404 $varnt = Title::newFromText( $v, $ns );
405 if( $varnt && $varnt->getArticleID() > 0 ) {
406 $nt = $varnt;
407 if( !$wgDisableLangConversion )
408 $link = $v;
409 break;
410 }
411 }
412 }
413
414 /**
415 * returns language specific hash options
416 *
417 * @access public
418 */
419 function getExtraHashOptions() {
420 $variant = $this->getPreferredVariant();
421 return '!' . $variant ;
422 }
423
424 /**
425 * get title text as defined in the body of the article text
426 *
427 * @access public
428 */
429 function getParsedTitle() {
430 return $this->mTitleDisplay;
431 }
432
433 /**
434 * a write lock to the cache
435 *
436 * @private
437 */
438 function lockCache() {
439 global $wgMemc;
440 $success = false;
441 for($i=0; $i<30; $i++) {
442 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
443 break;
444 sleep(1);
445 }
446 return $success;
447 }
448
449 /**
450 * unlock cache
451 *
452 * @private
453 */
454 function unlockCache() {
455 global $wgMemc;
456 $wgMemc->delete($this->mCacheKey . "lock");
457 }
458
459
460 /**
461 * Load default conversion tables
462 * This method must be implemented in derived class
463 *
464 * @private
465 */
466 function loadDefaultTables() {
467 $name = get_class($this);
468 wfDie("Must implement loadDefaultTables() method in class $name");
469 }
470
471 /**
472 * load conversion tables either from the cache or the disk
473 * @private
474 */
475 function loadTables($fromcache=true) {
476 global $wgMemc;
477 if( $this->mTablesLoaded )
478 return;
479 $this->mTablesLoaded = true;
480 if($fromcache) {
481 $this->mTables = $wgMemc->get( $this->mCacheKey );
482 if( !empty( $this->mTables ) ) //all done
483 return;
484 }
485 // not in cache, or we need a fresh reload.
486 // we will first load the default tables
487 // then update them using things in MediaWiki:Zhconversiontable/*
488 global $wgMessageCache;
489 $this->loadDefaultTables();
490 foreach($this->mVariants as $var) {
491 $cached = $this->parseCachedTable($var);
492 $this->mTables[$var] = array_merge($this->mTables[$var], $cached);
493 }
494
495 $this->postLoadTables();
496
497 if($this->lockCache()) {
498 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
499 $this->unlockCache();
500 }
501 }
502
503 /**
504 * Hook for post processig after conversion tables are loaded
505 *
506 */
507 function postLoadTables() {}
508
509 /**
510 * Reload the conversion tables
511 *
512 * @private
513 */
514 function reloadTables() {
515 if($this->mTables)
516 unset($this->mTables);
517 $this->mTablesLoaded = false;
518 $this->loadTables(false);
519 }
520
521
522 /**
523 * parse the conversion table stored in the cache
524 *
525 * the tables should be in blocks of the following form:
526
527 * -{
528 * word => word ;
529 * word => word ;
530 * ...
531 * }-
532 *
533 * to make the tables more manageable, subpages are allowed
534 * and will be parsed recursively if $recursive=true
535 *
536 * @private
537 */
538 function parseCachedTable($code, $subpage='', $recursive=true) {
539 global $wgMessageCache;
540 static $parsed = array();
541
542 if(!is_object($wgMessageCache))
543 return array();
544
545 $key = 'Conversiontable/'.$code;
546 if($subpage)
547 $key .= '/' . $subpage;
548
549 if(array_key_exists($key, $parsed))
550 return array();
551
552
553 $txt = $wgMessageCache->get( $key, true, true, true );
554
555 // get all subpage links of the form
556 // [[MediaWiki:conversiontable/zh-xx/...|...]]
557 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
558 $subs = explode('[[', $txt);
559 $sublinks = array();
560 foreach( $subs as $sub ) {
561 $link = explode(']]', $sub, 2);
562 if(count($link) != 2)
563 continue;
564 $b = explode('|', $link[0]);
565 $b = explode('/', trim($b[0]), 3);
566 if(count($b)==3)
567 $sublink = $b[2];
568 else
569 $sublink = '';
570
571 if($b[0] == $linkhead && $b[1] == $code) {
572 $sublinks[] = $sublink;
573 }
574 }
575
576
577 // parse the mappings in this page
578 $blocks = explode($this->mMarkup['begin'], $txt);
579 array_shift($blocks);
580 $ret = array();
581 foreach($blocks as $block) {
582 $mappings = explode($this->mMarkup['end'], $block, 2);
583 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
584 $table = explode( ';', $stripped );
585 foreach( $table as $t ) {
586 $m = explode( '=>', $t );
587 if( count( $m ) != 2)
588 continue;
589 // trim any trailling comments starting with '//'
590 $tt = explode('//', $m[1], 2);
591 $ret[trim($m[0])] = trim($tt[0]);
592 }
593 }
594 $parsed[$key] = true;
595
596
597 // recursively parse the subpages
598 if($recursive) {
599 foreach($sublinks as $link) {
600 $s = $this->parseCachedTable($code, $link, $recursive);
601 $ret = array_merge($ret, $s);
602 }
603 }
604
605 if ($this->mUcfirst) {
606 foreach ($ret as $k => $v) {
607 $ret[LanguageUtf8::ucfirst($k)] = LanguageUtf8::ucfirst($v);
608 }
609 }
610 return $ret;
611 }
612
613 /**
614 * Enclose a string with the "no conversion" tag. This is used by
615 * various functions in the Parser
616 *
617 * @param string $text text to be tagged for no conversion
618 * @return string the tagged text
619 */
620 function markNoConversion($text) {
621 # don't mark if already marked
622 if(strpos($text, $this->mMarkup['begin']) ||
623 strpos($text, $this->mMarkup['end']))
624 return $text;
625
626 $ret = $this->mMarkup['begin'] . $text . $this->mMarkup['end'];
627 return $ret;
628 }
629
630 /**
631 * convert the sorting key for category links. this should make different
632 * keys that are variants of each other map to the same key
633 */
634 function convertCategoryKey( $key ) {
635 return $key;
636 }
637 /**
638 * hook to refresh the cache of conversion tables when
639 * MediaWiki:conversiontable* is updated
640 * @private
641 */
642 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
643 $titleobj = $article->getTitle();
644 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
645 /*
646 global $wgContLang; // should be an LanguageZh.
647 if(get_class($wgContLang) != 'languagezh')
648 return true;
649 */
650 $title = $titleobj->getDBkey();
651 $t = explode('/', $title, 3);
652 $c = count($t);
653 if( $c > 1 && $t[0] == 'Conversiontable' ) {
654 if(in_array($t[1], $this->mVariants)) {
655 $this->reloadTables();
656 }
657 }
658 }
659 return true;
660 }
661 }
662
663 ?>