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