Mention Postgres alternative.
[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 $mUseFss = false;
16 var $mTables;
17 var $mFssObjects;
18 var $mTitleDisplay='';
19 var $mDoTitleConvert=true, $mDoContentConvert=true;
20 var $mCacheKey;
21 var $mLangObj;
22 var $mMarkup;
23 var $mFlags;
24 var $mUcfirst = false;
25 var $mNoTitleConvert = false;
26 /**
27 * Constructor
28 *
29 * @param string $maincode the main language code of this language
30 * @param array $variants the supported variants of this language
31 * @param array $variantfallback the fallback language of each variant
32 * @param array $markup array defining the markup used for manual conversion
33 * @param array $flags array defining the custom strings that maps to the flags
34 * @access public
35 */
36 function __construct($langobj, $maincode,
37 $variants=array(),
38 $variantfallbacks=array(),
39 $markup=array(),
40 $flags = array()) {
41 global $wgDBname;
42 global $wgLegalTitleChars;
43 $this->mLangObj = $langobj;
44 $this->mMainLanguageCode = $maincode;
45 $this->mVariants = $variants;
46 $this->mVariantFallbacks = $variantfallbacks;
47 $this->mCacheKey = $wgDBname . ":conversiontables";
48 $m = array('begin'=>'-{', 'flagsep'=>'|', 'codesep'=>':',
49 'varsep'=>';', 'end'=>'}-');
50 $this->mMarkup = array_merge($m, $markup);
51 $f = array('A'=>'A', 'T'=>'T');
52 $this->mFlags = array_merge($f, $flags);
53 if ( function_exists( 'fss_prep_replace' ) ) {
54 $this->mUseFss = true;
55 }
56 }
57
58 /**
59 * @access public
60 */
61 function getVariants() {
62 return $this->mVariants;
63 }
64
65 /**
66 * in case some variant is not defined in the markup, we need
67 * to have some fallback. for example, in zh, normally people
68 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
69 * when zh-sg is preferred but not defined, we will pick zh-cn
70 * in this case. right now this is only used by zh.
71 *
72 * @param string $v the language code of the variant
73 * @return string the code of the fallback language or false if there is no fallback
74 * @private
75 */
76 function getVariantFallback($v) {
77 return $this->mVariantFallbacks[$v];
78 }
79
80
81 /**
82 * get preferred language variants.
83 * @param boolean $fromUser Get it from $wgUser's preferences
84 * @return string the preferred language code
85 * @access public
86 */
87 function getPreferredVariant( $fromUser = true ) {
88 global $wgUser, $wgRequest;
89
90 if($this->mPreferredVariant)
91 return $this->mPreferredVariant;
92
93 // see if the preference is set in the request
94 $req = $wgRequest->getText( 'variant' );
95 if( in_array( $req, $this->mVariants ) ) {
96 $this->mPreferredVariant = $req;
97 return $req;
98 }
99
100 // get language variant preference from logged in users
101 // Don't call this on stub objects because that causes infinite
102 // recursion during initialisation
103 if( $fromUser && $wgUser->isLoggedIn() ) {
104 $this->mPreferredVariant = $wgUser->getOption('variant');
105 return $this->mPreferredVariant;
106 }
107
108 # FIXME rewrite code for parsing http header. The current code
109 # is written specific for detecting zh- variants
110 if( !$this->mPreferredVariant ) {
111 // see if some supported language variant is set in the
112 // http header, but we don't set the mPreferredVariant
113 // variable in case this is called before the user's
114 // preference is loaded
115 $pv=$this->mMainLanguageCode;
116 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
117 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
118 $zh = strstr($header, 'zh-');
119 if($zh) {
120 $pv = substr($zh,0,5);
121 }
122 }
123 return $pv;
124 }
125 }
126
127 /**
128 * dictionary-based conversion
129 *
130 * @param string $text the text to be converted
131 * @param string $toVariant the target language code
132 * @return string the converted text
133 * @private
134 */
135 function autoConvert($text, $toVariant=false) {
136 $fname="LanguageConverter::autoConvert";
137
138 wfProfileIn( $fname );
139
140 if(!$this->mTablesLoaded)
141 $this->loadTables();
142
143 if(!$toVariant)
144 $toVariant = $this->getPreferredVariant();
145 if(!in_array($toVariant, $this->mVariants))
146 return $text;
147
148 /* we convert everything except:
149 1. html markups (anything between < and >)
150 2. html entities
151 3. place holders created by the parser
152 */
153 global $wgParser;
154 if (isset($wgParser))
155 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
156 else
157 $marker = "";
158
159 // this one is needed when the text is inside an html markup
160 $htmlfix = '|<[^>]+$|^[^<>]*>';
161
162 // disable convert to variants between <code></code> tags
163 $codefix = '<code>.+?<\/code>|';
164
165 $reg = '/'.$codefix.'<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
166
167 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
168
169 $m = array_shift($matches);
170
171 $ret = $this->translate($m[0], $toVariant);
172 $mstart = $m[1]+strlen($m[0]);
173 foreach($matches as $m) {
174 $ret .= substr($text, $mstart, $m[1]-$mstart);
175 $ret .= $this->translate($m[0], $toVariant);
176 $mstart = $m[1] + strlen($m[0]);
177 }
178 wfProfileOut( $fname );
179 return $ret;
180 }
181
182 /**
183 * Translate a string to a variant
184 * Doesn't process markup or do any of that other stuff, for that use convert()
185 *
186 * @param string $text Text to convert
187 * @param string $variant Variant language code
188 * @return string Translated text
189 */
190 function translate( $text, $variant ) {
191 if( !$this->mTablesLoaded )
192 $this->loadTables();
193 if ( $this->mUseFss ) {
194 return fss_exec_replace( $this->mFssObjects[$variant], $text );
195 } else {
196 return strtr( $text, $this->mTables[$variant] );
197 }
198 }
199
200 /**
201 * convert text to all supported variants
202 *
203 * @param string $text the text to be converted
204 * @return array of string
205 * @public
206 */
207 function autoConvertToAllVariants($text) {
208 $fname="LanguageConverter::autoConvertToAllVariants";
209 wfProfileIn( $fname );
210 if( !$this->mTablesLoaded )
211 $this->loadTables();
212
213 $ret = array();
214 foreach($this->mVariants as $variant) {
215 $ret[$variant] = $this->translate($text, $variant);
216 }
217
218 wfProfileOut( $fname );
219 return $ret;
220 }
221
222 /**
223 * convert link text to all supported variants
224 *
225 * @param string $text the text to be converted
226 * @return array of string
227 * @public
228 */
229 function convertLinkToAllVariants($text) {
230 if( !$this->mTablesLoaded )
231 $this->loadTables();
232
233 $ret = array();
234 $tarray = explode($this->mMarkup['begin'], $text);
235 $tfirst = array_shift($tarray);
236
237 foreach($this->mVariants as $variant)
238 $ret[$variant] = $this->translate($tfirst,$variant);
239
240 foreach($tarray as $txt) {
241 $marked = explode($this->mMarkup['end'], $txt, 2);
242
243 foreach($this->mVariants as $variant){
244 $ret[$variant] .= $this->mMarkup['begin'].$marked[0].$this->mMarkup['end'];
245 if(array_key_exists(1, $marked))
246 $ret[$variant] .= $this->translate($marked[1],$variant);
247 }
248
249 }
250
251 return $ret;
252 }
253
254
255 /**
256 * Convert text using a parser object for context
257 */
258 function parserConvert( $text, &$parser ) {
259 global $wgDisableLangConversion;
260 /* don't do anything if this is the conversion table */
261 if ( $parser->mTitle->getNamespace() == NS_MEDIAWIKI &&
262 strpos($parser->mTitle->getText(), "Conversiontable") !== false )
263 {
264 return $text;
265 }
266
267 if($wgDisableLangConversion)
268 return $text;
269
270 $text = $this->convert( $text );
271 $parser->mOutput->setTitleText( $this->mTitleDisplay );
272 return $text;
273 }
274
275 /**
276 * convert text to different variants of a language. the automatic
277 * conversion is done in autoConvert(). here we parse the text
278 * marked with -{}-, which specifies special conversions of the
279 * text that can not be accomplished in autoConvert()
280 *
281 * syntax of the markup:
282 * -{code1:text1;code2:text2;...}- or
283 * -{text}- in which case no conversion should take place for text
284 *
285 * @param string $text text to be converted
286 * @param bool $isTitle whether this conversion is for the article title
287 * @return string converted text
288 * @access public
289 */
290 function convert( $text , $isTitle=false) {
291 $mw =& MagicWord::get( 'notitleconvert' );
292 if( $mw->matchAndRemove( $text ) )
293 $this->mDoTitleConvert = false;
294
295 $mw =& MagicWord::get( 'nocontentconvert' );
296 if( $mw->matchAndRemove( $text ) ) {
297 $this->mDoContentConvert = false;
298 }
299
300 // no conversion if redirecting
301 $mw =& MagicWord::get( 'redirect' );
302 if( $mw->matchStart( $text ))
303 return $text;
304
305 if( $isTitle ) {
306 if($this->mNoTitleConvert){
307 $this->mTitleDisplay = $text;
308 return $text;
309 }
310
311 if( !$this->mDoTitleConvert ) {
312 $this->mTitleDisplay = $text;
313 return $text;
314 }
315
316 global $wgRequest;
317 $isredir = $wgRequest->getText( 'redirect', 'yes' );
318 $action = $wgRequest->getText( 'action' );
319 if ( $isredir == 'no' || $action == 'edit' ) {
320 return $text;
321 }
322 else {
323 $this->mTitleDisplay = $this->convert($text);
324 return $this->mTitleDisplay;
325 }
326 }
327
328 if( !$this->mDoContentConvert )
329 return $text;
330
331 $plang = $this->getPreferredVariant();
332 if( isset( $this->mVariantFallbacks[$plang] ) ) {
333 $fallback = $this->mVariantFallbacks[$plang];
334 } else {
335 // This sounds... bad?
336 $fallback = '';
337 }
338
339 $tarray = explode($this->mMarkup['begin'], $text);
340 $tfirst = array_shift($tarray);
341 $text = $this->autoConvert($tfirst);
342 foreach($tarray as $txt) {
343 $marked = explode($this->mMarkup['end'], $txt, 2);
344 $flags = array();
345 $tt = explode($this->mMarkup['flagsep'], $marked[0], 2);
346
347 if(sizeof($tt) == 2) {
348 $f = explode($this->mMarkup['varsep'], $tt[0]);
349 foreach($f as $ff) {
350 $ff = trim($ff);
351 if(array_key_exists($ff, $this->mFlags) &&
352 !array_key_exists($this->mFlags[$ff], $flags))
353 $flags[] = $this->mFlags[$ff];
354 }
355 $rules = $tt[1];
356 }
357 else
358 $rules = $marked[0];
359
360 //FIXME: may cause trouble here...
361 //strip &nbsp; since it interferes with the parsing, plus,
362 //all spaces should be stripped in this tag anyway.
363 $rules = str_replace('&nbsp;', '', $rules);
364
365 $carray = $this->parseManualRule($rules, $flags);
366 $disp = '';
367 if(array_key_exists($plang, $carray))
368 $disp = $carray[$plang];
369 else if(array_key_exists($fallback, $carray))
370 $disp = $carray[$fallback];
371 if($disp) {
372 if(in_array('T', $flags))
373 $this->mTitleDisplay = $disp;
374 else
375 $text .= $disp;
376
377 if(in_array('A', $flags)) {
378 /* modify the conversion table for this session*/
379
380 /* fill in the missing variants, if any,
381 with fallbacks */
382 foreach($this->mVariants as $v) {
383 if(!array_key_exists($v, $carray)) {
384 $vf = $this->getVariantFallback($v);
385 if(array_key_exists($vf, $carray))
386 $carray[$v] = $carray[$vf];
387 }
388 }
389
390 foreach($this->mVariants as $vfrom) {
391 if(!array_key_exists($vfrom, $carray))
392 continue;
393 foreach($this->mVariants as $vto) {
394 if($vfrom == $vto)
395 continue;
396 if(!array_key_exists($vto, $carray))
397 continue;
398 $this->mTables[$vto][$carray[$vfrom]] = $carray[$vto];
399
400 }
401 }
402 if ( $this->mUseFss ) {
403 $this->generateFssObjects();
404 }
405 }
406 }
407 else {
408 $text .= $marked[0];
409 }
410 if(array_key_exists(1, $marked))
411 $text .= $this->autoConvert($marked[1]);
412 }
413
414 return $text;
415 }
416
417 /**
418 * parse the manually marked conversion rule
419 * @param string $rule the text of the rule
420 * @return array of the translation in each variant
421 * @private
422 */
423 function parseManualRule($rules, $flags=array()) {
424
425 $choice = explode($this->mMarkup['varsep'], $rules);
426 $carray = array();
427 if(sizeof($choice) == 1) {
428 /* a single choice */
429 foreach($this->mVariants as $v)
430 $carray[$v] = $choice[0];
431 }
432 else {
433 foreach($choice as $c) {
434 $v = explode($this->mMarkup['codesep'], $c);
435 if(sizeof($v) != 2) // syntax error, skip
436 continue;
437 $carray[trim($v[0])] = trim($v[1]);
438 }
439 }
440 return $carray;
441 }
442
443 /**
444 * if a language supports multiple variants, it is
445 * possible that non-existing link in one variant
446 * actually exists in another variant. this function
447 * tries to find it. See e.g. LanguageZh.php
448 *
449 * @param string $link the name of the link
450 * @param mixed $nt the title object of the link
451 * @return null the input parameters may be modified upon return
452 * @access public
453 */
454 function findVariantLink( &$link, &$nt ) {
455 global $wgDisableLangConversion;
456 $pref = $this->getPreferredVariant();
457 $ns=0;
458 if(is_object($nt))
459 $ns = $nt->getNamespace();
460
461 $variants = $this->autoConvertToAllVariants($link);
462 if($variants == false) //give up
463 return;
464 foreach( $variants as $v ) {
465 $varnt = Title::newFromText( $v, $ns );
466 if( $varnt && $varnt->getArticleID() > 0 ) {
467 $nt = $varnt;
468 if( !$wgDisableLangConversion )
469 $link = $v;
470 break;
471 }
472 }
473 }
474
475 /**
476 * returns language specific hash options
477 *
478 * @access public
479 */
480 function getExtraHashOptions() {
481 $variant = $this->getPreferredVariant();
482 return '!' . $variant ;
483 }
484
485 /**
486 * get title text as defined in the body of the article text
487 *
488 * @access public
489 */
490 function getParsedTitle() {
491 return $this->mTitleDisplay;
492 }
493
494 /**
495 * a write lock to the cache
496 *
497 * @private
498 */
499 function lockCache() {
500 global $wgMemc;
501 $success = false;
502 for($i=0; $i<30; $i++) {
503 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
504 break;
505 sleep(1);
506 }
507 return $success;
508 }
509
510 /**
511 * unlock cache
512 *
513 * @private
514 */
515 function unlockCache() {
516 global $wgMemc;
517 $wgMemc->delete($this->mCacheKey . "lock");
518 }
519
520
521 /**
522 * Load default conversion tables
523 * This method must be implemented in derived class
524 *
525 * @private
526 */
527 function loadDefaultTables() {
528 $name = get_class($this);
529 wfDie("Must implement loadDefaultTables() method in class $name");
530 }
531
532 /**
533 * load conversion tables either from the cache or the disk
534 * @private
535 */
536 function loadTables($fromcache=true) {
537 global $wgMemc;
538 if( $this->mTablesLoaded )
539 return;
540 $this->mTablesLoaded = true;
541 if($fromcache) {
542 $this->mTables = $wgMemc->get( $this->mCacheKey );
543 if( !empty( $this->mTables ) ) //all done
544 return;
545 }
546 // not in cache, or we need a fresh reload.
547 // we will first load the default tables
548 // then update them using things in MediaWiki:Zhconversiontable/*
549 global $wgMessageCache;
550 $this->loadDefaultTables();
551 foreach($this->mVariants as $var) {
552 $cached = $this->parseCachedTable($var);
553 $this->mTables[$var] = array_merge($this->mTables[$var], $cached);
554 }
555
556 $this->postLoadTables();
557
558 if($this->lockCache()) {
559 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
560 $this->unlockCache();
561 }
562 if ( $this->mUseFss ) {
563 $this->generateFssObjects();
564 }
565 }
566
567 /**
568 * Generate FSS objects. The FSS extension must be available.
569 */
570 function generateFssObjects() {
571 foreach ( $this->mTables as $variant => $table ) {
572 $this->mFssObjects[$variant] = fss_prep_replace( $table );
573 }
574 }
575
576 /**
577 * Hook for post processig after conversion tables are loaded
578 *
579 */
580 function postLoadTables() {}
581
582 /**
583 * Reload the conversion tables
584 *
585 * @private
586 */
587 function reloadTables() {
588 if($this->mTables)
589 unset($this->mTables);
590 $this->mTablesLoaded = false;
591 $this->loadTables(false);
592 }
593
594
595 /**
596 * parse the conversion table stored in the cache
597 *
598 * the tables should be in blocks of the following form:
599
600 * -{
601 * word => word ;
602 * word => word ;
603 * ...
604 * }-
605 *
606 * to make the tables more manageable, subpages are allowed
607 * and will be parsed recursively if $recursive=true
608 *
609 * @private
610 */
611 function parseCachedTable($code, $subpage='', $recursive=true) {
612 global $wgMessageCache;
613 static $parsed = array();
614
615 if(!is_object($wgMessageCache))
616 return array();
617
618 $key = 'Conversiontable/'.$code;
619 if($subpage)
620 $key .= '/' . $subpage;
621
622 if(array_key_exists($key, $parsed))
623 return array();
624
625
626 $txt = $wgMessageCache->get( $key, true, true, true );
627
628 // get all subpage links of the form
629 // [[MediaWiki:conversiontable/zh-xx/...|...]]
630 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
631 $subs = explode('[[', $txt);
632 $sublinks = array();
633 foreach( $subs as $sub ) {
634 $link = explode(']]', $sub, 2);
635 if(count($link) != 2)
636 continue;
637 $b = explode('|', $link[0]);
638 $b = explode('/', trim($b[0]), 3);
639 if(count($b)==3)
640 $sublink = $b[2];
641 else
642 $sublink = '';
643
644 if($b[0] == $linkhead && $b[1] == $code) {
645 $sublinks[] = $sublink;
646 }
647 }
648
649
650 // parse the mappings in this page
651 $blocks = explode($this->mMarkup['begin'], $txt);
652 array_shift($blocks);
653 $ret = array();
654 foreach($blocks as $block) {
655 $mappings = explode($this->mMarkup['end'], $block, 2);
656 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
657 $table = explode( ';', $stripped );
658 foreach( $table as $t ) {
659 $m = explode( '=>', $t );
660 if( count( $m ) != 2)
661 continue;
662 // trim any trailling comments starting with '//'
663 $tt = explode('//', $m[1], 2);
664 $ret[trim($m[0])] = trim($tt[0]);
665 }
666 }
667 $parsed[$key] = true;
668
669
670 // recursively parse the subpages
671 if($recursive) {
672 foreach($sublinks as $link) {
673 $s = $this->parseCachedTable($code, $link, $recursive);
674 $ret = array_merge($ret, $s);
675 }
676 }
677
678 if ($this->mUcfirst) {
679 foreach ($ret as $k => $v) {
680 $ret[Language::ucfirst($k)] = Language::ucfirst($v);
681 }
682 }
683 return $ret;
684 }
685
686 /**
687 * Enclose a string with the "no conversion" tag. This is used by
688 * various functions in the Parser
689 *
690 * @param string $text text to be tagged for no conversion
691 * @return string the tagged text
692 */
693 function markNoConversion($text, $noParse=false) {
694 # don't mark if already marked
695 if(strpos($text, $this->mMarkup['begin']) ||
696 strpos($text, $this->mMarkup['end']))
697 return $text;
698
699 $ret = $this->mMarkup['begin'] . $text . $this->mMarkup['end'];
700 return $ret;
701 }
702
703 /**
704 * convert the sorting key for category links. this should make different
705 * keys that are variants of each other map to the same key
706 */
707 function convertCategoryKey( $key ) {
708 return $key;
709 }
710 /**
711 * hook to refresh the cache of conversion tables when
712 * MediaWiki:conversiontable* is updated
713 * @private
714 */
715 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
716 $titleobj = $article->getTitle();
717 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
718 /*
719 global $wgContLang; // should be an LanguageZh.
720 if(get_class($wgContLang) != 'languagezh')
721 return true;
722 */
723 $title = $titleobj->getDBkey();
724 $t = explode('/', $title, 3);
725 $c = count($t);
726 if( $c > 1 && $t[0] == 'Conversiontable' ) {
727 if(in_array($t[1], $this->mVariants)) {
728 $this->reloadTables();
729 }
730 }
731 }
732 return true;
733 }
734
735 function setNoTitleConvert(){
736 $this->mNoTitleConvert = true;
737 }
738
739 }
740
741 ?>