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