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