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