Merged r16826-16858 of branches/SerbianVariants.
[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 $script = $_SERVER['SCRIPT_NAME'];
101 $variants = implode('|',$this->mVariants);
102 if(preg_match("/($variants)$/",$script,$matches)){
103 $this->mPreferredVariant = $matches[1];
104 return $this->mPreferredVariant;
105 }
106
107 // get language variant preference from logged in users
108 // Don't call this on stub objects because that causes infinite
109 // recursion during initialisation
110 if( $fromUser && $wgUser->isLoggedIn() ) {
111 $this->mPreferredVariant = $wgUser->getOption('variant');
112 return $this->mPreferredVariant;
113 }
114
115 # FIXME rewrite code for parsing http header. The current code
116 # is written specific for detecting zh- variants
117 if( !$this->mPreferredVariant ) {
118 // see if some supported language variant is set in the
119 // http header, but we don't set the mPreferredVariant
120 // variable in case this is called before the user's
121 // preference is loaded
122 $pv=$this->mMainLanguageCode;
123 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
124 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
125 $zh = strstr($header, 'zh-');
126 if($zh) {
127 $pv = substr($zh,0,5);
128 }
129 }
130 return $pv;
131 }
132 }
133
134 /**
135 * dictionary-based conversion
136 *
137 * @param string $text the text to be converted
138 * @param string $toVariant the target language code
139 * @return string the converted text
140 * @private
141 */
142 function autoConvert($text, $toVariant=false) {
143 $fname="LanguageConverter::autoConvert";
144
145 wfProfileIn( $fname );
146
147 if(!$this->mTablesLoaded)
148 $this->loadTables();
149
150 if(!$toVariant)
151 $toVariant = $this->getPreferredVariant();
152 if(!in_array($toVariant, $this->mVariants))
153 return $text;
154
155 /* we convert everything except:
156 1. html markups (anything between < and >)
157 2. html entities
158 3. place holders created by the parser
159 */
160 global $wgParser;
161 if (isset($wgParser))
162 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
163 else
164 $marker = "";
165
166 // this one is needed when the text is inside an html markup
167 $htmlfix = '|<[^>]+$|^[^<>]*>';
168
169 // disable convert to variants between <code></code> tags
170 $codefix = '<code>.+?<\/code>|';
171
172 $reg = '/'.$codefix.'<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
173
174 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
175
176 $m = array_shift($matches);
177
178 $ret = $this->translate($m[0], $toVariant);
179 $mstart = $m[1]+strlen($m[0]);
180 foreach($matches as $m) {
181 $ret .= substr($text, $mstart, $m[1]-$mstart);
182 $ret .= $this->translate($m[0], $toVariant);
183 $mstart = $m[1] + strlen($m[0]);
184 }
185 wfProfileOut( $fname );
186 return $ret;
187 }
188
189 /**
190 * Translate a string to a variant
191 * Doesn't process markup or do any of that other stuff, for that use convert()
192 *
193 * @param string $text Text to convert
194 * @param string $variant Variant language code
195 * @return string Translated text
196 */
197 function translate( $text, $variant ) {
198 if( !$this->mTablesLoaded )
199 $this->loadTables();
200 if ( $this->mUseFss ) {
201 return fss_exec_replace( $this->mFssObjects[$variant], $text );
202 } else {
203 return strtr( $text, $this->mTables[$variant] );
204 }
205 }
206
207 /**
208 * convert text to all supported variants
209 *
210 * @param string $text the text to be converted
211 * @return array of string
212 * @public
213 */
214 function autoConvertToAllVariants($text) {
215 $fname="LanguageConverter::autoConvertToAllVariants";
216 wfProfileIn( $fname );
217 if( !$this->mTablesLoaded )
218 $this->loadTables();
219
220 $ret = array();
221 foreach($this->mVariants as $variant) {
222 $ret[$variant] = $this->translate($text, $variant);
223 }
224
225 wfProfileOut( $fname );
226 return $ret;
227 }
228
229 /**
230 * convert link text to all supported variants
231 *
232 * @param string $text the text to be converted
233 * @return array of string
234 * @public
235 */
236 function convertLinkToAllVariants($text) {
237 if( !$this->mTablesLoaded )
238 $this->loadTables();
239
240 $ret = array();
241 $tarray = explode($this->mMarkup['begin'], $text);
242 $tfirst = array_shift($tarray);
243
244 foreach($this->mVariants as $variant)
245 $ret[$variant] = $this->translate($tfirst,$variant);
246
247 foreach($tarray as $txt) {
248 $marked = explode($this->mMarkup['end'], $txt, 2);
249
250 foreach($this->mVariants as $variant){
251 $ret[$variant] .= $this->mMarkup['begin'].$marked[0].$this->mMarkup['end'];
252 if(array_key_exists(1, $marked))
253 $ret[$variant] .= $this->translate($marked[1],$variant);
254 }
255
256 }
257
258 return $ret;
259 }
260
261
262 /**
263 * Convert text using a parser object for context
264 */
265 function parserConvert( $text, &$parser ) {
266 global $wgDisableLangConversion;
267 /* don't do anything if this is the conversion table */
268 if ( $parser->mTitle->getNamespace() == NS_MEDIAWIKI &&
269 strpos($parser->mTitle->getText(), "Conversiontable") !== false )
270 {
271 return $text;
272 }
273
274 if($wgDisableLangConversion)
275 return $text;
276
277 $text = $this->convert( $text );
278 $parser->mOutput->setTitleText( $this->mTitleDisplay );
279 return $text;
280 }
281
282 /**
283 * convert text to different variants of a language. the automatic
284 * conversion is done in autoConvert(). here we parse the text
285 * marked with -{}-, which specifies special conversions of the
286 * text that can not be accomplished in autoConvert()
287 *
288 * syntax of the markup:
289 * -{code1:text1;code2:text2;...}- or
290 * -{text}- in which case no conversion should take place for text
291 *
292 * @param string $text text to be converted
293 * @param bool $isTitle whether this conversion is for the article title
294 * @return string converted text
295 * @access public
296 */
297 function convert( $text , $isTitle=false) {
298 $mw =& MagicWord::get( 'notitleconvert' );
299 if( $mw->matchAndRemove( $text ) )
300 $this->mDoTitleConvert = false;
301
302 $mw =& MagicWord::get( 'nocontentconvert' );
303 if( $mw->matchAndRemove( $text ) ) {
304 $this->mDoContentConvert = false;
305 }
306
307 // no conversion if redirecting
308 $mw =& MagicWord::get( 'redirect' );
309 if( $mw->matchStart( $text ))
310 return $text;
311
312 if( $isTitle ) {
313 if($this->mNoTitleConvert){
314 $this->mTitleDisplay = $text;
315 return $text;
316 }
317
318 if( !$this->mDoTitleConvert ) {
319 $this->mTitleDisplay = $text;
320 return $text;
321 }
322
323 global $wgRequest;
324 $isredir = $wgRequest->getText( 'redirect', 'yes' );
325 $action = $wgRequest->getText( 'action' );
326 if ( $isredir == 'no' || $action == 'edit' ) {
327 return $text;
328 }
329 else {
330 $this->mTitleDisplay = $this->convert($text);
331 return $this->mTitleDisplay;
332 }
333 }
334
335 if( !$this->mDoContentConvert )
336 return $text;
337
338 $plang = $this->getPreferredVariant();
339 if( isset( $this->mVariantFallbacks[$plang] ) ) {
340 $fallback = $this->mVariantFallbacks[$plang];
341 } else {
342 // This sounds... bad?
343 $fallback = '';
344 }
345
346 $tarray = explode($this->mMarkup['begin'], $text);
347 $tfirst = array_shift($tarray);
348 $text = $this->autoConvert($tfirst);
349 foreach($tarray as $txt) {
350 $marked = explode($this->mMarkup['end'], $txt, 2);
351 $flags = array();
352 $tt = explode($this->mMarkup['flagsep'], $marked[0], 2);
353
354 if(sizeof($tt) == 2) {
355 $f = explode($this->mMarkup['varsep'], $tt[0]);
356 foreach($f as $ff) {
357 $ff = trim($ff);
358 if(array_key_exists($ff, $this->mFlags) &&
359 !array_key_exists($this->mFlags[$ff], $flags))
360 $flags[] = $this->mFlags[$ff];
361 }
362 $rules = $tt[1];
363 }
364 else
365 $rules = $marked[0];
366
367 //FIXME: may cause trouble here...
368 //strip &nbsp; since it interferes with the parsing, plus,
369 //all spaces should be stripped in this tag anyway.
370 $rules = str_replace('&nbsp;', '', $rules);
371
372 $carray = $this->parseManualRule($rules, $flags);
373 $disp = '';
374 if(array_key_exists($plang, $carray))
375 $disp = $carray[$plang];
376 else if(array_key_exists($fallback, $carray))
377 $disp = $carray[$fallback];
378 if($disp) {
379 if(in_array('T', $flags))
380 $this->mTitleDisplay = $disp;
381 else
382 $text .= $disp;
383
384 if(in_array('A', $flags)) {
385 /* modify the conversion table for this session*/
386
387 /* fill in the missing variants, if any,
388 with fallbacks */
389 foreach($this->mVariants as $v) {
390 if(!array_key_exists($v, $carray)) {
391 $vf = $this->getVariantFallback($v);
392 if(array_key_exists($vf, $carray))
393 $carray[$v] = $carray[$vf];
394 }
395 }
396
397 foreach($this->mVariants as $vfrom) {
398 if(!array_key_exists($vfrom, $carray))
399 continue;
400 foreach($this->mVariants as $vto) {
401 if($vfrom == $vto)
402 continue;
403 if(!array_key_exists($vto, $carray))
404 continue;
405 $this->mTables[$vto][$carray[$vfrom]] = $carray[$vto];
406
407 }
408 }
409 if ( $this->mUseFss ) {
410 $this->generateFssObjects();
411 }
412 }
413 }
414 else {
415 $text .= $marked[0];
416 }
417 if(array_key_exists(1, $marked))
418 $text .= $this->autoConvert($marked[1]);
419 }
420
421 return $text;
422 }
423
424 /**
425 * parse the manually marked conversion rule
426 * @param string $rule the text of the rule
427 * @return array of the translation in each variant
428 * @private
429 */
430 function parseManualRule($rules, $flags=array()) {
431
432 $choice = explode($this->mMarkup['varsep'], $rules);
433 $carray = array();
434 if(sizeof($choice) == 1) {
435 /* a single choice */
436 foreach($this->mVariants as $v)
437 $carray[$v] = $choice[0];
438 }
439 else {
440 foreach($choice as $c) {
441 $v = explode($this->mMarkup['codesep'], $c);
442 if(sizeof($v) != 2) // syntax error, skip
443 continue;
444 $carray[trim($v[0])] = trim($v[1]);
445 }
446 }
447 return $carray;
448 }
449
450 /**
451 * if a language supports multiple variants, it is
452 * possible that non-existing link in one variant
453 * actually exists in another variant. this function
454 * tries to find it. See e.g. LanguageZh.php
455 *
456 * @param string $link the name of the link
457 * @param mixed $nt the title object of the link
458 * @return null the input parameters may be modified upon return
459 * @access public
460 */
461 function findVariantLink( &$link, &$nt ) {
462 global $wgDisableLangConversion;
463 $pref = $this->getPreferredVariant();
464 $ns=0;
465 if(is_object($nt))
466 $ns = $nt->getNamespace();
467
468 $variants = $this->autoConvertToAllVariants($link);
469 if($variants == false) //give up
470 return;
471 foreach( $variants as $v ) {
472 $varnt = Title::newFromText( $v, $ns );
473 if( $varnt && $varnt->getArticleID() > 0 ) {
474 $nt = $varnt;
475 if( !$wgDisableLangConversion )
476 $link = $v;
477 break;
478 }
479 }
480 }
481
482 /**
483 * returns language specific hash options
484 *
485 * @access public
486 */
487 function getExtraHashOptions() {
488 $variant = $this->getPreferredVariant();
489 return '!' . $variant ;
490 }
491
492 /**
493 * get title text as defined in the body of the article text
494 *
495 * @access public
496 */
497 function getParsedTitle() {
498 return $this->mTitleDisplay;
499 }
500
501 /**
502 * a write lock to the cache
503 *
504 * @private
505 */
506 function lockCache() {
507 global $wgMemc;
508 $success = false;
509 for($i=0; $i<30; $i++) {
510 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
511 break;
512 sleep(1);
513 }
514 return $success;
515 }
516
517 /**
518 * unlock cache
519 *
520 * @private
521 */
522 function unlockCache() {
523 global $wgMemc;
524 $wgMemc->delete($this->mCacheKey . "lock");
525 }
526
527
528 /**
529 * Load default conversion tables
530 * This method must be implemented in derived class
531 *
532 * @private
533 */
534 function loadDefaultTables() {
535 $name = get_class($this);
536 wfDie("Must implement loadDefaultTables() method in class $name");
537 }
538
539 /**
540 * load conversion tables either from the cache or the disk
541 * @private
542 */
543 function loadTables($fromcache=true) {
544 global $wgMemc;
545 if( $this->mTablesLoaded )
546 return;
547 $this->mTablesLoaded = true;
548 if($fromcache) {
549 $this->mTables = $wgMemc->get( $this->mCacheKey );
550 if( !empty( $this->mTables ) ) //all done
551 return;
552 }
553 // not in cache, or we need a fresh reload.
554 // we will first load the default tables
555 // then update them using things in MediaWiki:Zhconversiontable/*
556 global $wgMessageCache;
557 $this->loadDefaultTables();
558 foreach($this->mVariants as $var) {
559 $cached = $this->parseCachedTable($var);
560 $this->mTables[$var] = array_merge($this->mTables[$var], $cached);
561 }
562
563 $this->postLoadTables();
564
565 if($this->lockCache()) {
566 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
567 $this->unlockCache();
568 }
569 if ( $this->mUseFss ) {
570 $this->generateFssObjects();
571 }
572 }
573
574 /**
575 * Generate FSS objects. The FSS extension must be available.
576 */
577 function generateFssObjects() {
578 foreach ( $this->mTables as $variant => $table ) {
579 $this->mFssObjects[$variant] = fss_prep_replace( $table );
580 }
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 function setNoTitleConvert(){
743 $this->mNoTitleConvert = true;
744 }
745
746 }
747
748 ?>