* Fixed up metadata
[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 //strip &nbsp; since it interferes with the parsing, plus,
245 //all spaces should be stripped in this tag anyway.
246 $marked[0] = str_replace('&nbsp;', '', $marked[0]);
247
248 /* see if this conversion has special meaning
249 # for article title:
250 -{T|zh-cn:foo;zh-tw:bar}-
251 # convert all occurence of foo/bar in this article:
252 -{A|zh-cn:foo;zh-tw:bar}-
253 */
254 $flag = '';
255 $choice = false;
256 $tt = explode("|", $marked[0], 2);
257 if(sizeof($tt) == 2) {
258 $flag = trim($tt[0]);
259 $choice = explode(";", $tt[1]);
260 }
261
262 if(!$choice) {
263 $choice = explode($this->mMarkup['varsep'], $marked[0]);
264 }
265 $disp = '';
266 $carray = array();
267 if(!array_key_exists(1, $choice)) {
268 /* a single choice */
269 $disp = $choice[0];
270
271 /* fill the carray if the conversion is for the whole article*/
272 if($flag == 'A') {
273 foreach($this->mVariants as $v) {
274 $carray[$v] = $disp;
275 }
276 }
277 }
278 else {
279 foreach($choice as $c) {
280 $v = explode($this->mMarkup['codesep'], $c);
281 if(sizeof($v) != 2) // syntax error, skip
282 continue;
283 $carray[trim($v[0])] = trim($v[1]);
284 }
285 if(array_key_exists($plang, $carray))
286 $disp = $carray[$plang];
287 else if(array_key_exists($fallback, $carray))
288 $disp = $carray[$fallback];
289 }
290 if(empty($disp)) { // syntax error
291 $text .= $marked[0];
292 }
293 else {
294 if($flag == 'T') // for title only
295 $this->mTitleDisplay = $disp;
296 else {
297 $text .= $disp;
298 if($flag == 'A') {
299 /* modify the conversion table for this session*/
300
301 /* fill in the missing variants, if any,
302 with fallbacks */
303 foreach($this->mVariants as $v) {
304 if(!array_key_exists($v, $carray)) {
305 $vf = $this->getVariantFallback($v);
306 if(array_key_exists($vf, $carray))
307 $carray[$v] = $carray[$vf];
308 }
309 }
310 foreach($this->mVariants as $vfrom) {
311 if(!array_key_exists($vfrom, $carray))
312 continue;
313 foreach($this->mVariants as $vto) {
314 if($vfrom == $vto)
315 continue;
316 if(!array_key_exists($vto, $carray))
317 continue;
318 $this->mTables[$vto][$carray[$vfrom]] = $carray[$vto];
319 }
320 }
321 }
322 }
323 }
324 if(array_key_exists(1, $marked))
325 $text .= $this->autoConvert($marked[1]);
326 }
327
328 return $text;
329 }
330
331
332 /**
333 * if a language supports multiple variants, it is
334 * possible that non-existing link in one variant
335 * actually exists in another variant. this function
336 * tries to find it. See e.g. LanguageZh.php
337 *
338 * @param string $link the name of the link
339 * @param mixed $nt the title object of the link
340 * @return null the input parameters may be modified upon return
341 * @access public
342 */
343 function findVariantLink( &$link, &$nt ) {
344 static $count=0; //used to limit this operation
345 static $cache=array();
346 global $wgDisableLangConversion;
347 $pref = $this->getPreferredVariant();
348 if( $count > 50 )
349 return;
350 $count++;
351 $variants = $this->autoConvertToAllVariants($link);
352 if($variants == false) //give up
353 return;
354 foreach( $variants as $v ) {
355 if(isset($cache[$v]))
356 continue;
357 $cache[$v] = 1;
358 $varnt = Title::newFromText( $v );
359 if( $varnt && $varnt->getArticleID() > 0 ) {
360 $nt = $varnt;
361 if( !$wgDisableLangConversion && $pref != 'zh' )
362 $link = $v;
363 break;
364 }
365 }
366 }
367
368 /**
369 * returns language specific hash options
370 *
371 * @access public
372 */
373 function getExtraHashOptions() {
374 $variant = $this->getPreferredVariant();
375 return '!' . $variant ;
376 }
377
378 /**
379 * get title text as defined in the body of the article text
380 *
381 * @access public
382 */
383 function getParsedTitle() {
384 return $this->mTitleDisplay;
385 }
386
387 /**
388 * a write lock to the cache
389 *
390 * @access private
391 */
392 function lockCache() {
393 global $wgMemc;
394 $success = false;
395 for($i=0; $i<30; $i++) {
396 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
397 break;
398 sleep(1);
399 }
400 return $success;
401 }
402
403 /**
404 * unlock cache
405 *
406 * @access private
407 */
408 function unlockCache() {
409 global $wgMemc;
410 $wgMemc->delete($this->mCacheKey . "lock");
411 }
412
413
414 /**
415 * Load default conversion tables
416 * This method must be implemented in derived class
417 *
418 * @access private
419 */
420 function loadDefaultTables() {
421 $name = get_class($this);
422 die("Must implement loadDefaultTables() method in class $name");
423 }
424
425 /**
426 * load conversion tables either from the cache or the disk
427 * @access private
428 */
429 function loadTables($fromcache=true) {
430 global $wgMemc;
431 if( $this->mTablesLoaded )
432 return;
433 $this->mTablesLoaded = true;
434 if($fromcache) {
435 $this->mTables = $wgMemc->get( $this->mCacheKey );
436 if( !empty( $this->mTables ) ) //all done
437 return;
438 }
439 // not in cache, or we need a fresh reload.
440 // we will first load the default tables
441 // then update them using things in MediaWiki:Zhconversiontable/*
442 global $wgMessageCache;
443 $this->loadDefaultTables();
444 foreach($this->mVariants as $var) {
445 $cached = $this->parseCachedTable($var);
446 $this->mTables[$var] = array_merge($this->mTables[$var], $cached);
447 }
448
449 $this->postLoadTables();
450
451 if($this->lockCache()) {
452 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
453 $this->unlockCache();
454 }
455 }
456
457 /**
458 * Hook for post processig after conversion tables are loaded
459 *
460 */
461 function postLoadTables() {}
462
463 /* deprecated? */
464 function updateTablexxxx($code, $table) {
465 global $wgMemc;
466 if(!$this->mTablesLoaded)
467 $this->loadTables();
468
469 $this->mTables[$code] = array_merge($this->mTables[$code], $table);
470 if($this->lockCache()) {
471 $wgMemc->delete($this->mCacheKey);
472 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
473 $this->unlockCache();
474 }
475 }
476
477 /**
478 * Reload the conversion tables
479 *
480 * @access private
481 */
482 function reloadTables() {
483 if($this->mTables)
484 unset($this->mTables);
485 $this->mTablesLoaded = false;
486 $this->loadTables(false);
487 }
488
489
490 /**
491 * parse the conversion table stored in the cache
492 *
493 * the tables should be in blocks of the following form:
494
495 * -{
496 * word => word ;
497 * word => word ;
498 * ...
499 * }-
500 *
501 * to make the tables more manageable, subpages are allowed
502 * and will be parsed recursively if $recursive=true
503 *
504 * @access private
505 */
506 function parseCachedTable($code, $subpage='', $recursive=true) {
507 global $wgMessageCache;
508 static $parsed = array();
509
510 if(!is_object($wgMessageCache))
511 return array();
512
513 $key = 'Conversiontable/'.$code;
514 if($subpage)
515 $key .= '/' . $subpage;
516
517 if(array_key_exists($key, $parsed))
518 return array();
519
520
521 $txt = $wgMessageCache->get( $key, true, true, true );
522
523 // get all subpage links of the form
524 // [[MediaWiki:conversiontable/zh-xx/...|...]]
525 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
526 $subs = explode('[[', $txt);
527 $sublinks = array();
528 foreach( $subs as $sub ) {
529 $link = explode(']]', $sub, 2);
530 if(count($link) != 2)
531 continue;
532 $b = explode('|', $link[0]);
533 $b = explode('/', trim($b[0]), 3);
534 if(count($b)==3)
535 $sublink = $b[2];
536 else
537 $sublink = '';
538
539 if($b[0] == $linkhead && $b[1] == $code) {
540 $sublinks[] = $sublink;
541 }
542 }
543
544
545 // parse the mappings in this page
546 $blocks = explode('-{', $txt);
547 array_shift($blocks);
548 $ret = array();
549 foreach($blocks as $block) {
550 $mappings = explode('}-', $block, 2);
551 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
552 $table = explode( ';', $stripped );
553 foreach( $table as $t ) {
554 $m = explode( '=>', $t );
555 if( count( $m ) != 2)
556 continue;
557 // trim any trailling comments starting with '//'
558 $tt = explode('//', $m[1], 2);
559 $ret[trim($m[0])] = trim($tt[0]);
560 }
561 }
562 $parsed[$key] = true;
563
564
565 // recursively parse the subpages
566 if($recursive) {
567 foreach($sublinks as $link) {
568 $s = $this->parseCachedTable($code, $link, $recursive);
569 $ret = array_merge($ret, $s);
570 }
571 }
572 return $ret;
573 }
574
575 /**
576 * Enclose a string with the "no conversion" tag. This is used by
577 * various functions in the Parser
578 *
579 * @param string $text text to be tagged for no conversion
580 * @return string the tagged text
581 */
582 function markNoConversion($text) {
583 $ret = $this->mMarkup['begin'] . $text . $this->mMarkup['end'];
584 }
585
586 /**
587 * hook to refresh the cache of conversion tables when
588 * MediaWiki:conversiontable* is updated
589 * @access private
590 */
591 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
592 $titleobj = $article->getTitle();
593 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
594 /*
595 global $wgContLang; // should be an LanguageZh.
596 if(get_class($wgContLang) != 'languagezh')
597 return true;
598 */
599 $title = $titleobj->getDBkey();
600 $t = explode('/', $title, 3);
601 $c = count($t);
602 if( $c > 1 && $t[0] == 'Conversiontable' ) {
603 if(in_array($t[1], $this->mVariants)) {
604 $this->reloadTables();
605 }
606 }
607 }
608 return true;
609 }
610 }
611
612 ?>