* Make variant table caching a little more robust, using main language code
[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 $wgLegalTitleChars;
39 $this->mLangObj = $langobj;
40 $this->mMainLanguageCode = $maincode;
41 $this->mVariants = $variants;
42 $this->mVariantFallbacks = $variantfallbacks;
43 $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
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 * @param boolean $fromUser Get it from $wgUser's preferences
77 * @return string the preferred language code
78 * @access public
79 */
80 function getPreferredVariant( $fromUser = true ) {
81 global $wgUser, $wgRequest, $wgVariantArticlePath;
82
83 if($this->mPreferredVariant)
84 return $this->mPreferredVariant;
85
86 // see if the preference is set in the request
87 $req = $wgRequest->getText( 'variant' );
88 if( in_array( $req, $this->mVariants ) ) {
89 $this->mPreferredVariant = $req;
90 return $req;
91 }
92
93 // check the syntax /code/ArticleTitle
94 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
95 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
96 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
97 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
98 if(in_array($scriptBase,$this->mVariants)){
99 $this->mPreferredVariant = $scriptBase;
100 return $this->mPreferredVariant;
101 }
102 }
103
104 // get language variant preference from logged in users
105 // Don't call this on stub objects because that causes infinite
106 // recursion during initialisation
107 if( $fromUser && $wgUser->isLoggedIn() ) {
108 $this->mPreferredVariant = $wgUser->getOption('variant');
109 return $this->mPreferredVariant;
110 }
111
112 # FIXME rewrite code for parsing http header. The current code
113 # is written specific for detecting zh- variants
114 if( !$this->mPreferredVariant ) {
115 // see if some supported language variant is set in the
116 // http header, but we don't set the mPreferredVariant
117 // variable in case this is called before the user's
118 // preference is loaded
119 $pv=$this->mMainLanguageCode;
120 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
121 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
122 $zh = strstr($header, $pv.'-');
123 if($zh) {
124 $pv = substr($zh,0,5);
125 }
126 }
127 return $pv;
128 }
129 }
130
131 /**
132 * dictionary-based conversion
133 *
134 * @param string $text the text to be converted
135 * @param string $toVariant the target language code
136 * @return string the converted text
137 * @private
138 */
139 function autoConvert($text, $toVariant=false) {
140 $fname="LanguageConverter::autoConvert";
141
142 wfProfileIn( $fname );
143
144 if(!$this->mTablesLoaded)
145 $this->loadTables();
146
147 if(!$toVariant)
148 $toVariant = $this->getPreferredVariant();
149 if(!in_array($toVariant, $this->mVariants))
150 return $text;
151
152 /* we convert everything except:
153 1. html markups (anything between < and >)
154 2. html entities
155 3. place holders created by the parser
156 */
157 global $wgParser;
158 if (isset($wgParser))
159 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
160 else
161 $marker = "";
162
163 // this one is needed when the text is inside an html markup
164 $htmlfix = '|<[^>]+$|^[^<>]*>';
165
166 // disable convert to variants between <code></code> tags
167 $codefix = '<code>.+?<\/code>|';
168 // disable convertsion of <script type="text/javascript"> ... </script>
169 $scriptfix = '<script.*?>.*?<\/script>|';
170
171 $reg = '/'.$codefix . $scriptfix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
172
173 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
174
175 $m = array_shift($matches);
176
177 $ret = $this->translate($m[0], $toVariant);
178 $mstart = $m[1]+strlen($m[0]);
179 foreach($matches as $m) {
180 $ret .= substr($text, $mstart, $m[1]-$mstart);
181 $ret .= $this->translate($m[0], $toVariant);
182 $mstart = $m[1] + strlen($m[0]);
183 }
184 wfProfileOut( $fname );
185 return $ret;
186 }
187
188 /**
189 * Translate a string to a variant
190 * Doesn't process markup or do any of that other stuff, for that use convert()
191 *
192 * @param string $text Text to convert
193 * @param string $variant Variant language code
194 * @return string Translated text
195 */
196 function translate( $text, $variant ) {
197 wfProfileIn( __METHOD__ );
198 if( !$this->mTablesLoaded )
199 $this->loadTables();
200 $text = $this->mTables[$variant]->replace( $text );
201 wfProfileOut( __METHOD__ );
202 return $text;
203 }
204
205 /**
206 * convert text to all supported variants
207 *
208 * @param string $text the text to be converted
209 * @return array of string
210 * @public
211 */
212 function autoConvertToAllVariants($text) {
213 $fname="LanguageConverter::autoConvertToAllVariants";
214 wfProfileIn( $fname );
215 if( !$this->mTablesLoaded )
216 $this->loadTables();
217
218 $ret = array();
219 foreach($this->mVariants as $variant) {
220 $ret[$variant] = $this->translate($text, $variant);
221 }
222
223 wfProfileOut( $fname );
224 return $ret;
225 }
226
227 /**
228 * convert link text to all supported variants
229 *
230 * @param string $text the text to be converted
231 * @return array of string
232 * @public
233 */
234 function convertLinkToAllVariants($text) {
235 if( !$this->mTablesLoaded )
236 $this->loadTables();
237
238 $ret = array();
239 $tarray = explode($this->mMarkup['begin'], $text);
240 $tfirst = array_shift($tarray);
241
242 foreach($this->mVariants as $variant)
243 $ret[$variant] = $this->translate($tfirst,$variant);
244
245 foreach($tarray as $txt) {
246 $marked = explode($this->mMarkup['end'], $txt, 2);
247
248 foreach($this->mVariants as $variant){
249 $ret[$variant] .= $this->mMarkup['begin'].$marked[0].$this->mMarkup['end'];
250 if(array_key_exists(1, $marked))
251 $ret[$variant] .= $this->translate($marked[1],$variant);
252 }
253
254 }
255
256 return $ret;
257 }
258
259
260 /**
261 * Convert text using a parser object for context
262 */
263 function parserConvert( $text, &$parser ) {
264 global $wgDisableLangConversion;
265 /* don't do anything if this is the conversion table */
266 if ( $parser->mTitle->getNamespace() == NS_MEDIAWIKI &&
267 strpos($parser->mTitle->getText(), "Conversiontable") !== false )
268 {
269 return $text;
270 }
271
272 if($wgDisableLangConversion)
273 return $text;
274
275 $text = $this->convert( $text );
276 $parser->mOutput->setTitleText( $this->mTitleDisplay );
277 return $text;
278 }
279
280 /**
281 * convert text to different variants of a language. the automatic
282 * conversion is done in autoConvert(). here we parse the text
283 * marked with -{}-, which specifies special conversions of the
284 * text that can not be accomplished in autoConvert()
285 *
286 * syntax of the markup:
287 * -{code1:text1;code2:text2;...}- or
288 * -{text}- in which case no conversion should take place for text
289 *
290 * @param string $text text to be converted
291 * @param bool $isTitle whether this conversion is for the article title
292 * @return string converted text
293 * @access public
294 */
295 function convert( $text , $isTitle=false) {
296 $mw =& MagicWord::get( 'notitleconvert' );
297 if( $mw->matchAndRemove( $text ) )
298 $this->mDoTitleConvert = false;
299
300 $mw =& MagicWord::get( 'nocontentconvert' );
301 if( $mw->matchAndRemove( $text ) ) {
302 $this->mDoContentConvert = false;
303 }
304
305 // no conversion if redirecting
306 $mw =& MagicWord::get( 'redirect' );
307 if( $mw->matchStart( $text ))
308 return $text;
309
310 if( $isTitle ) {
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]->setPair($carray[$vfrom], $carray[$vto]);
399 }
400 }
401 }
402 }
403 else {
404 $text .= $marked[0];
405 }
406 if(array_key_exists(1, $marked))
407 $text .= $this->autoConvert($marked[1]);
408 }
409
410 return $text;
411 }
412
413 /**
414 * parse the manually marked conversion rule
415 * @param string $rule the text of the rule
416 * @return array of the translation in each variant
417 * @private
418 */
419 function parseManualRule($rules, $flags=array()) {
420
421 $choice = explode($this->mMarkup['varsep'], $rules);
422 $carray = array();
423 if(sizeof($choice) == 1) {
424 /* a single choice */
425 foreach($this->mVariants as $v)
426 $carray[$v] = $choice[0];
427 }
428 else {
429 foreach($choice as $c) {
430 $v = explode($this->mMarkup['codesep'], $c);
431 if(sizeof($v) != 2) // syntax error, skip
432 continue;
433 $carray[trim($v[0])] = trim($v[1]);
434 }
435 }
436 return $carray;
437 }
438
439 /**
440 * if a language supports multiple variants, it is
441 * possible that non-existing link in one variant
442 * actually exists in another variant. this function
443 * tries to find it. See e.g. LanguageZh.php
444 *
445 * @param string $link the name of the link
446 * @param mixed $nt the title object of the link
447 * @return null the input parameters may be modified upon return
448 * @access public
449 */
450 function findVariantLink( &$link, &$nt ) {
451 global $wgDisableLangConversion;
452 $linkBatch = new LinkBatch();
453
454 $ns=NS_MAIN;
455
456 if(is_object($nt))
457 $ns = $nt->getNamespace();
458
459 $variants = $this->autoConvertToAllVariants($link);
460 if($variants == false) //give up
461 return;
462
463 $titles = array();
464
465 foreach( $variants as $v ) {
466 if($v != $link){
467 $varnt = Title::newFromText( $v, $ns );
468 if(!is_null($varnt)){
469 $linkBatch->addObj($varnt);
470 $titles[]=$varnt;
471 }
472 }
473 }
474
475 // fetch all variants in single query
476 $linkBatch->execute();
477
478 foreach( $titles as $varnt ) {
479 if( $varnt->getArticleID() > 0 ) {
480 $nt = $varnt;
481 if( !$wgDisableLangConversion )
482 $link = $v;
483 break;
484 }
485 }
486 }
487
488 /**
489 * returns language specific hash options
490 *
491 * @access public
492 */
493 function getExtraHashOptions() {
494 $variant = $this->getPreferredVariant();
495 return '!' . $variant ;
496 }
497
498 /**
499 * get title text as defined in the body of the article text
500 *
501 * @access public
502 */
503 function getParsedTitle() {
504 return $this->mTitleDisplay;
505 }
506
507 /**
508 * a write lock to the cache
509 *
510 * @private
511 */
512 function lockCache() {
513 global $wgMemc;
514 $success = false;
515 for($i=0; $i<30; $i++) {
516 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
517 break;
518 sleep(1);
519 }
520 return $success;
521 }
522
523 /**
524 * unlock cache
525 *
526 * @private
527 */
528 function unlockCache() {
529 global $wgMemc;
530 $wgMemc->delete($this->mCacheKey . "lock");
531 }
532
533
534 /**
535 * Load default conversion tables
536 * This method must be implemented in derived class
537 *
538 * @private
539 */
540 function loadDefaultTables() {
541 $name = get_class($this);
542 wfDie("Must implement loadDefaultTables() method in class $name");
543 }
544
545 /**
546 * load conversion tables either from the cache or the disk
547 * @private
548 */
549 function loadTables($fromcache=true) {
550 global $wgMemc;
551 if( $this->mTablesLoaded )
552 return;
553 wfProfileIn( __METHOD__ );
554 $this->mTablesLoaded = true;
555 $this->mTables = false;
556 if($fromcache) {
557 wfProfileIn( __METHOD__.'-cache' );
558 $this->mTables = $wgMemc->get( $this->mCacheKey );
559 wfProfileOut( __METHOD__.'-cache' );
560 }
561 if ( !$this->mTables || !isset( $this->mTables['VERSION 2'] ) ) {
562 wfProfileIn( __METHOD__.'-recache' );
563 // not in cache, or we need a fresh reload.
564 // we will first load the default tables
565 // then update them using things in MediaWiki:Zhconversiontable/*
566 global $wgMessageCache;
567 $this->loadDefaultTables();
568 foreach($this->mVariants as $var) {
569 $cached = $this->parseCachedTable($var);
570 $this->mTables[$var]->mergeArray($cached);
571 }
572
573 $this->postLoadTables();
574 $this->mTables['VERSION 2'] = true;
575
576 if($this->lockCache()) {
577 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
578 $this->unlockCache();
579 }
580 wfProfileOut( __METHOD__.'-recache' );
581 }
582 wfProfileOut( __METHOD__ );
583 }
584
585 /**
586 * Hook for post processig after conversion tables are loaded
587 *
588 */
589 function postLoadTables() {}
590
591 /**
592 * Reload the conversion tables
593 *
594 * @private
595 */
596 function reloadTables() {
597 if($this->mTables)
598 unset($this->mTables);
599 $this->mTablesLoaded = false;
600 $this->loadTables(false);
601 }
602
603
604 /**
605 * parse the conversion table stored in the cache
606 *
607 * the tables should be in blocks of the following form:
608
609 * -{
610 * word => word ;
611 * word => word ;
612 * ...
613 * }-
614 *
615 * to make the tables more manageable, subpages are allowed
616 * and will be parsed recursively if $recursive=true
617 *
618 * @private
619 */
620 function parseCachedTable($code, $subpage='', $recursive=true) {
621 global $wgMessageCache;
622 static $parsed = array();
623
624 if(!is_object($wgMessageCache))
625 return array();
626
627 $key = 'Conversiontable/'.$code;
628 if($subpage)
629 $key .= '/' . $subpage;
630
631 if(array_key_exists($key, $parsed))
632 return array();
633
634
635 $txt = $wgMessageCache->get( $key, true, true, true );
636
637 // get all subpage links of the form
638 // [[MediaWiki:conversiontable/zh-xx/...|...]]
639 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
640 $subs = explode('[[', $txt);
641 $sublinks = array();
642 foreach( $subs as $sub ) {
643 $link = explode(']]', $sub, 2);
644 if(count($link) != 2)
645 continue;
646 $b = explode('|', $link[0]);
647 $b = explode('/', trim($b[0]), 3);
648 if(count($b)==3)
649 $sublink = $b[2];
650 else
651 $sublink = '';
652
653 if($b[0] == $linkhead && $b[1] == $code) {
654 $sublinks[] = $sublink;
655 }
656 }
657
658
659 // parse the mappings in this page
660 $blocks = explode($this->mMarkup['begin'], $txt);
661 array_shift($blocks);
662 $ret = array();
663 foreach($blocks as $block) {
664 $mappings = explode($this->mMarkup['end'], $block, 2);
665 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
666 $table = explode( ';', $stripped );
667 foreach( $table as $t ) {
668 $m = explode( '=>', $t );
669 if( count( $m ) != 2)
670 continue;
671 // trim any trailling comments starting with '//'
672 $tt = explode('//', $m[1], 2);
673 $ret[trim($m[0])] = trim($tt[0]);
674 }
675 }
676 $parsed[$key] = true;
677
678
679 // recursively parse the subpages
680 if($recursive) {
681 foreach($sublinks as $link) {
682 $s = $this->parseCachedTable($code, $link, $recursive);
683 $ret = array_merge($ret, $s);
684 }
685 }
686
687 if ($this->mUcfirst) {
688 foreach ($ret as $k => $v) {
689 $ret[Language::ucfirst($k)] = Language::ucfirst($v);
690 }
691 }
692 return $ret;
693 }
694
695 /**
696 * Enclose a string with the "no conversion" tag. This is used by
697 * various functions in the Parser
698 *
699 * @param string $text text to be tagged for no conversion
700 * @return string the tagged text
701 */
702 function markNoConversion($text, $noParse=false) {
703 # don't mark if already marked
704 if(strpos($text, $this->mMarkup['begin']) ||
705 strpos($text, $this->mMarkup['end']))
706 return $text;
707
708 $ret = $this->mMarkup['begin'] . $text . $this->mMarkup['end'];
709 return $ret;
710 }
711
712 /**
713 * convert the sorting key for category links. this should make different
714 * keys that are variants of each other map to the same key
715 */
716 function convertCategoryKey( $key ) {
717 return $key;
718 }
719 /**
720 * hook to refresh the cache of conversion tables when
721 * MediaWiki:conversiontable* is updated
722 * @private
723 */
724 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
725 $titleobj = $article->getTitle();
726 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
727 /*
728 global $wgContLang; // should be an LanguageZh.
729 if(get_class($wgContLang) != 'languagezh')
730 return true;
731 */
732 $title = $titleobj->getDBkey();
733 $t = explode('/', $title, 3);
734 $c = count($t);
735 if( $c > 1 && $t[0] == 'Conversiontable' ) {
736 if(in_array($t[1], $this->mVariants)) {
737 $this->reloadTables();
738 }
739 }
740 }
741 return true;
742 }
743
744 /**
745 * Armour rendered math against conversion
746 * Default is do nothing, since the process can interfere with
747 * parseManualRule() if format -{ alter1 ; alter2 }- is enabled
748 */
749 function armourMath($text){
750 return $text;
751 }
752
753
754 }
755
756 ?>