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