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