Some updates
[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
139 $reg = '/<[^>]+>|&[a-z#][a-z0-9]+;|'.UNIQ_PREFIX.'-[a-zA-Z0-9]+/';
140 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
141
142
143 $m = array_shift($matches);
144 $ret = strtr($m[0], $this->mTables[$toVariant]);
145 $mstart = $m[1]+strlen($m[0]);
146 foreach($matches as $m) {
147 $ret .= substr($text, $mstart, $m[1]-$mstart);
148 $ret .= strtr($m[0], $this->mTables[$toVariant]);
149 $mstart = $m[1] + strlen($m[0]);
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 global $wgTitle;
194
195 /* don't do anything if this is the conversion table */
196 if($wgTitle->getNamespace() == NS_MEDIAWIKI &&
197 strpos($wgTitle->getText(), "Conversiontable")!==false)
198 return $text;
199
200 if($wgDisableLangConversion)
201 return $text;
202
203 $mw =& MagicWord::get( MAG_NOTITLECONVERT );
204 if( $mw->matchAndRemove( $text ) )
205 $this->mDoTitleConvert = false;
206
207 $mw =& MagicWord::get( MAG_NOCONTENTCONVERT );
208 if( $mw->matchAndRemove( $text ) ) {
209 $this->mDoContentConvert = false;
210 }
211
212 // no conversion if redirecting
213 $mw =& MagicWord::get( MAG_REDIRECT );
214 if( $mw->matchStart( $text ))
215 return $text;
216
217 if( $isTitle ) {
218 if( !$this->mDoTitleConvert ) {
219 $this->mTitleDisplay = $text;
220 return $text;
221 }
222 if( !empty($this->mTitleDisplay))
223 return $this->mTitleDisplay;
224
225 global $wgRequest;
226 $isredir = $wgRequest->getText( 'redirect', 'yes' );
227 $action = $wgRequest->getText( 'action' );
228 if ( $isredir == 'no' || $action == 'edit' ) {
229 return $text;
230 }
231 else {
232 $this->mTitleDisplay = $this->autoConvert($text);
233 return $this->mTitleDisplay;
234 }
235 }
236
237 if( !$this->mDoContentConvert )
238 return $text;
239
240 $plang = $this->getPreferredVariant();
241 $fallback = $this->mVariantFallbacks[$plang];
242
243 $tarray = explode($this->mMarkup['begin'], $text);
244 $tfirst = array_shift($tarray);
245 $text = $this->autoConvert($tfirst);
246 foreach($tarray as $txt) {
247 $marked = explode($this->mMarkup['end'], $txt);
248 $flags = array();
249 $tt = explode($this->mMarkup['flagsep'], $marked[0], 2);
250
251 if(sizeof($tt) == 2) {
252 $f = explode($this->mMarkup['varsep'], $tt[0]);
253 foreach($f as $ff) {
254 $ff = trim($ff);
255 if(array_key_exists($ff, $this->mFlags) &&
256 !array_key_exists($this->mFlags[$ff], $flags))
257 $flags[] = $this->mFlags[$ff];
258 }
259 $rules = $tt[1];
260 }
261 else
262 $rules = $marked[0];
263
264 #FIXME: may cause trouble here...
265 //strip &nbsp; since it interferes with the parsing, plus,
266 //all spaces should be stripped in this tag anyway.
267 $rules = str_replace('&nbsp;', '', $rules);
268
269 $carray = $this->parseManualRule($rules, $flags);
270 $disp = '';
271 if(array_key_exists($plang, $carray))
272 $disp = $carray[$plang];
273 else if(array_key_exists($fallback, $carray))
274 $disp = $carray[$fallback];
275 if($disp) {
276 if(in_array('T', $flags))
277 $this->mTitleDisplay = $disp;
278 else
279 $text .= $disp;
280
281 if(in_array('A', $flags)) {
282 /* modify the conversion table for this session*/
283
284 /* fill in the missing variants, if any,
285 with fallbacks */
286 foreach($this->mVariants as $v) {
287 if(!array_key_exists($v, $carray)) {
288 $vf = $this->getVariantFallback($v);
289 if(array_key_exists($vf, $carray))
290 $carray[$v] = $carray[$vf];
291 }
292 }
293
294 foreach($this->mVariants as $vfrom) {
295 if(!array_key_exists($vfrom, $carray))
296 continue;
297 foreach($this->mVariants as $vto) {
298 if($vfrom == $vto)
299 continue;
300 if(!array_key_exists($vto, $carray))
301 continue;
302 $this->mTables[$vto][$carray[$vfrom]] = $carray[$vto];
303
304 }
305 }
306 }
307 }
308 else {
309 $text .= $marked[0];
310 }
311 if(array_key_exists(1, $marked))
312 $text .= $this->autoConvert($marked[1]);
313 }
314
315 return $text;
316 }
317
318 /**
319 * parse the manually marked conversion rule
320 * @param string $rule the text of the rule
321 * @return array of the translation in each variant
322 * @access private
323 */
324 function parseManualRule($rules, $flags=array()) {
325
326 $choice = explode($this->mMarkup['varsep'], $rules);
327 $carray = array();
328 if(sizeof($choice) == 1) {
329 /* a single choice */
330 foreach($this->mVariants as $v)
331 $carray[$v] = $choice[0];
332 }
333 else {
334 foreach($choice as $c) {
335 $v = explode($this->mMarkup['codesep'], $c);
336 if(sizeof($v) != 2) // syntax error, skip
337 continue;
338 $carray[trim($v[0])] = trim($v[1]);
339 }
340 }
341 return $carray;
342 }
343
344 /**
345 * if a language supports multiple variants, it is
346 * possible that non-existing link in one variant
347 * actually exists in another variant. this function
348 * tries to find it. See e.g. LanguageZh.php
349 *
350 * @param string $link the name of the link
351 * @param mixed $nt the title object of the link
352 * @return null the input parameters may be modified upon return
353 * @access public
354 */
355 function findVariantLink( &$link, &$nt ) {
356 static $count=0; //used to limit this operation
357 static $cache=array();
358 global $wgDisableLangConversion;
359 $pref = $this->getPreferredVariant();
360 $ns=0;
361 if(is_object($nt))
362 $ns = $nt->getNamespace();
363 if( $count > 50 && $ns != NS_CATEGORY )
364 return;
365 $count++;
366 $variants = $this->autoConvertToAllVariants($link);
367 if($variants == false) //give up
368 return;
369 foreach( $variants as $v ) {
370 if(isset($cache[$v]))
371 continue;
372 $cache[$v] = 1;
373 $varnt = Title::newFromText( $v );
374 if( $varnt && $varnt->getArticleID() > 0 ) {
375 $nt = $varnt;
376 if( !$wgDisableLangConversion )
377 $link = $v;
378 break;
379 }
380 }
381 }
382
383 /**
384 * returns language specific hash options
385 *
386 * @access public
387 */
388 function getExtraHashOptions() {
389 $variant = $this->getPreferredVariant();
390 return '!' . $variant ;
391 }
392
393 /**
394 * get title text as defined in the body of the article text
395 *
396 * @access public
397 */
398 function getParsedTitle() {
399 return $this->mTitleDisplay;
400 }
401
402 /**
403 * a write lock to the cache
404 *
405 * @access private
406 */
407 function lockCache() {
408 global $wgMemc;
409 $success = false;
410 for($i=0; $i<30; $i++) {
411 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
412 break;
413 sleep(1);
414 }
415 return $success;
416 }
417
418 /**
419 * unlock cache
420 *
421 * @access private
422 */
423 function unlockCache() {
424 global $wgMemc;
425 $wgMemc->delete($this->mCacheKey . "lock");
426 }
427
428
429 /**
430 * Load default conversion tables
431 * This method must be implemented in derived class
432 *
433 * @access private
434 */
435 function loadDefaultTables() {
436 $name = get_class($this);
437 die("Must implement loadDefaultTables() method in class $name");
438 }
439
440 /**
441 * load conversion tables either from the cache or the disk
442 * @access private
443 */
444 function loadTables($fromcache=true) {
445 global $wgMemc;
446 if( $this->mTablesLoaded )
447 return;
448 $this->mTablesLoaded = true;
449 if($fromcache) {
450 $this->mTables = $wgMemc->get( $this->mCacheKey );
451 if( !empty( $this->mTables ) ) //all done
452 return;
453 }
454 // not in cache, or we need a fresh reload.
455 // we will first load the default tables
456 // then update them using things in MediaWiki:Zhconversiontable/*
457 global $wgMessageCache;
458 $this->loadDefaultTables();
459 foreach($this->mVariants as $var) {
460 $cached = $this->parseCachedTable($var);
461 $this->mTables[$var] = array_merge($this->mTables[$var], $cached);
462 }
463
464 $this->postLoadTables();
465
466 if($this->lockCache()) {
467 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
468 $this->unlockCache();
469 }
470 }
471
472 /**
473 * Hook for post processig after conversion tables are loaded
474 *
475 */
476 function postLoadTables() {}
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($this->mMarkup['begin'], $txt);
548 array_shift($blocks);
549 $ret = array();
550 foreach($blocks as $block) {
551 $mappings = explode($this->mMarkup['end'], $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
574 if ($this->mUcfirst) {
575 foreach ($ret as $k => $v) {
576 $ret[LanguageUtf8::ucfirst($k)] = LanguageUtf8::ucfirst($v);
577 }
578 }
579 return $ret;
580 }
581
582 /**
583 * Enclose a string with the "no conversion" tag. This is used by
584 * various functions in the Parser
585 *
586 * @param string $text text to be tagged for no conversion
587 * @return string the tagged text
588 */
589 function markNoConversion($text) {
590 # don't mark if already marked
591 if(strpos($text, $this->mMarkup['begin']) ||
592 strpos($text, $this->mMarkup['end']))
593 return $text;
594
595 $ret = $this->mMarkup['begin'] . $text . $this->mMarkup['end'];
596 return $ret;
597 }
598
599 /**
600 * convert the sorting key for category links. this should make different
601 * keys that are variants of each other map to the same key
602 */
603 function convertCategoryKey( $key ) {
604 return $key;
605 }
606 /**
607 * hook to refresh the cache of conversion tables when
608 * MediaWiki:conversiontable* is updated
609 * @access private
610 */
611 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
612 $titleobj = $article->getTitle();
613 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
614 /*
615 global $wgContLang; // should be an LanguageZh.
616 if(get_class($wgContLang) != 'languagezh')
617 return true;
618 */
619 $title = $titleobj->getDBkey();
620 $t = explode('/', $title, 3);
621 $c = count($t);
622 if( $c > 1 && $t[0] == 'Conversiontable' ) {
623 if(in_array($t[1], $this->mVariants)) {
624 $this->reloadTables();
625 }
626 }
627 }
628 return true;
629 }
630 }
631
632 ?>