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