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