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