Forgot to bump up style version
[mediawiki.git] / languages / LanguageConverter.php
blob6cb1ad950a1c282b224c709e774c97b606cad237
1 <?php
2 /**
3 * @package MediaWiki
4 * @subpackage Language
6 * @author Zhengzhu Feng <zhengzhu@gmail.com>
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
8 */
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
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
36 function __construct($langobj, $maincode,
37 $variants=array(),
38 $variantfallbacks=array(),
39 $markup=array(),
40 $flags = array()) {
41 global $wgLegalTitleChars;
42 $this->mLangObj = $langobj;
43 $this->mMainLanguageCode = $maincode;
44 $this->mVariants = $variants;
45 $this->mVariantFallbacks = $variantfallbacks;
46 $this->mCacheKey = wfMemcKey( 'conversiontables' );
47 $m = array('begin'=>'-{', 'flagsep'=>'|', 'codesep'=>':',
48 'varsep'=>';', 'end'=>'}-');
49 $this->mMarkup = array_merge($m, $markup);
50 $f = array('A'=>'A', 'T'=>'T');
51 $this->mFlags = array_merge($f, $flags);
52 if ( function_exists( 'fss_prep_replace' ) ) {
53 $this->mUseFss = true;
57 /**
58 * @access public
60 function getVariants() {
61 return $this->mVariants;
64 /**
65 * in case some variant is not defined in the markup, we need
66 * to have some fallback. for example, in zh, normally people
67 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
68 * when zh-sg is preferred but not defined, we will pick zh-cn
69 * in this case. right now this is only used by zh.
71 * @param string $v the language code of the variant
72 * @return string the code of the fallback language or false if there is no fallback
73 * @private
75 function getVariantFallback($v) {
76 return $this->mVariantFallbacks[$v];
80 /**
81 * get preferred language variants.
82 * @param boolean $fromUser Get it from $wgUser's preferences
83 * @return string the preferred language code
84 * @access public
86 function getPreferredVariant( $fromUser = true ) {
87 global $wgUser, $wgRequest;
89 if($this->mPreferredVariant)
90 return $this->mPreferredVariant;
92 // see if the preference is set in the request
93 $req = $wgRequest->getText( 'variant' );
94 if( in_array( $req, $this->mVariants ) ) {
95 $this->mPreferredVariant = $req;
96 return $req;
99 // check the syntax /code/ArticleTitle
100 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
101 if(in_array($scriptBase,$this->mVariants)){
102 $this->mPreferredVariant = $scriptBase;
103 return $this->mPreferredVariant;
106 // get language variant preference from logged in users
107 // Don't call this on stub objects because that causes infinite
108 // recursion during initialisation
109 if( $fromUser && $wgUser->isLoggedIn() ) {
110 $this->mPreferredVariant = $wgUser->getOption('variant');
111 return $this->mPreferredVariant;
114 # FIXME rewrite code for parsing http header. The current code
115 # is written specific for detecting zh- variants
116 if( !$this->mPreferredVariant ) {
117 // see if some supported language variant is set in the
118 // http header, but we don't set the mPreferredVariant
119 // variable in case this is called before the user's
120 // preference is loaded
121 $pv=$this->mMainLanguageCode;
122 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
123 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
124 $zh = strstr($header, 'zh-');
125 if($zh) {
126 $pv = substr($zh,0,5);
129 return $pv;
134 * dictionary-based conversion
136 * @param string $text the text to be converted
137 * @param string $toVariant the target language code
138 * @return string the converted text
139 * @private
141 function autoConvert($text, $toVariant=false) {
142 $fname="LanguageConverter::autoConvert";
144 wfProfileIn( $fname );
146 if(!$this->mTablesLoaded)
147 $this->loadTables();
149 if(!$toVariant)
150 $toVariant = $this->getPreferredVariant();
151 if(!in_array($toVariant, $this->mVariants))
152 return $text;
154 /* we convert everything except:
155 1. html markups (anything between < and >)
156 2. html entities
157 3. place holders created by the parser
159 global $wgParser;
160 if (isset($wgParser))
161 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
162 else
163 $marker = "";
165 // this one is needed when the text is inside an html markup
166 $htmlfix = '|<[^>]+$|^[^<>]*>';
168 // disable convert to variants between <code></code> tags
169 $codefix = '<code>.+?<\/code>|';
171 $reg = '/'.$codefix.'<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
173 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
175 $m = array_shift($matches);
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]);
184 wfProfileOut( $fname );
185 return $ret;
189 * Translate a string to a variant
190 * Doesn't process markup or do any of that other stuff, for that use convert()
192 * @param string $text Text to convert
193 * @param string $variant Variant language code
194 * @return string Translated text
196 function translate( $text, $variant ) {
197 if( !$this->mTablesLoaded )
198 $this->loadTables();
199 if ( $this->mUseFss ) {
200 return fss_exec_replace( $this->mFssObjects[$variant], $text );
201 } else {
202 return strtr( $text, $this->mTables[$variant] );
207 * convert text to all supported variants
209 * @param string $text the text to be converted
210 * @return array of string
211 * @public
213 function autoConvertToAllVariants($text) {
214 $fname="LanguageConverter::autoConvertToAllVariants";
215 wfProfileIn( $fname );
216 if( !$this->mTablesLoaded )
217 $this->loadTables();
219 $ret = array();
220 foreach($this->mVariants as $variant) {
221 $ret[$variant] = $this->translate($text, $variant);
224 wfProfileOut( $fname );
225 return $ret;
229 * convert link text to all supported variants
231 * @param string $text the text to be converted
232 * @return array of string
233 * @public
235 function convertLinkToAllVariants($text) {
236 if( !$this->mTablesLoaded )
237 $this->loadTables();
239 $ret = array();
240 $tarray = explode($this->mMarkup['begin'], $text);
241 $tfirst = array_shift($tarray);
243 foreach($this->mVariants as $variant)
244 $ret[$variant] = $this->translate($tfirst,$variant);
246 foreach($tarray as $txt) {
247 $marked = explode($this->mMarkup['end'], $txt, 2);
249 foreach($this->mVariants as $variant){
250 $ret[$variant] .= $this->mMarkup['begin'].$marked[0].$this->mMarkup['end'];
251 if(array_key_exists(1, $marked))
252 $ret[$variant] .= $this->translate($marked[1],$variant);
257 return $ret;
262 * Convert text using a parser object for context
264 function parserConvert( $text, &$parser ) {
265 global $wgDisableLangConversion;
266 /* don't do anything if this is the conversion table */
267 if ( $parser->mTitle->getNamespace() == NS_MEDIAWIKI &&
268 strpos($parser->mTitle->getText(), "Conversiontable") !== false )
270 return $text;
273 if($wgDisableLangConversion)
274 return $text;
276 $text = $this->convert( $text );
277 $parser->mOutput->setTitleText( $this->mTitleDisplay );
278 return $text;
282 * convert text to different variants of a language. the automatic
283 * conversion is done in autoConvert(). here we parse the text
284 * marked with -{}-, which specifies special conversions of the
285 * text that can not be accomplished in autoConvert()
287 * syntax of the markup:
288 * -{code1:text1;code2:text2;...}- or
289 * -{text}- in which case no conversion should take place for text
291 * @param string $text text to be converted
292 * @param bool $isTitle whether this conversion is for the article title
293 * @return string converted text
294 * @access public
296 function convert( $text , $isTitle=false) {
297 $mw =& MagicWord::get( 'notitleconvert' );
298 if( $mw->matchAndRemove( $text ) )
299 $this->mDoTitleConvert = false;
301 $mw =& MagicWord::get( 'nocontentconvert' );
302 if( $mw->matchAndRemove( $text ) ) {
303 $this->mDoContentConvert = false;
306 // no conversion if redirecting
307 $mw =& MagicWord::get( 'redirect' );
308 if( $mw->matchStart( $text ))
309 return $text;
311 if( $isTitle ) {
312 if($this->mNoTitleConvert){
313 $this->mTitleDisplay = $text;
314 return $text;
317 if( !$this->mDoTitleConvert ) {
318 $this->mTitleDisplay = $text;
319 return $text;
322 global $wgRequest;
323 $isredir = $wgRequest->getText( 'redirect', 'yes' );
324 $action = $wgRequest->getText( 'action' );
325 if ( $isredir == 'no' || $action == 'edit' ) {
326 return $text;
328 else {
329 $this->mTitleDisplay = $this->convert($text);
330 return $this->mTitleDisplay;
334 if( !$this->mDoContentConvert )
335 return $text;
337 $plang = $this->getPreferredVariant();
338 if( isset( $this->mVariantFallbacks[$plang] ) ) {
339 $fallback = $this->mVariantFallbacks[$plang];
340 } else {
341 // This sounds... bad?
342 $fallback = '';
345 $tarray = explode($this->mMarkup['begin'], $text);
346 $tfirst = array_shift($tarray);
347 $text = $this->autoConvert($tfirst);
348 foreach($tarray as $txt) {
349 $marked = explode($this->mMarkup['end'], $txt, 2);
350 $flags = array();
351 $tt = explode($this->mMarkup['flagsep'], $marked[0], 2);
353 if(sizeof($tt) == 2) {
354 $f = explode($this->mMarkup['varsep'], $tt[0]);
355 foreach($f as $ff) {
356 $ff = trim($ff);
357 if(array_key_exists($ff, $this->mFlags) &&
358 !array_key_exists($this->mFlags[$ff], $flags))
359 $flags[] = $this->mFlags[$ff];
361 $rules = $tt[1];
363 else
364 $rules = $marked[0];
366 //FIXME: may cause trouble here...
367 //strip &nbsp; since it interferes with the parsing, plus,
368 //all spaces should be stripped in this tag anyway.
369 $rules = str_replace('&nbsp;', '', $rules);
371 $carray = $this->parseManualRule($rules, $flags);
372 $disp = '';
373 if(array_key_exists($plang, $carray))
374 $disp = $carray[$plang];
375 else if(array_key_exists($fallback, $carray))
376 $disp = $carray[$fallback];
377 if($disp) {
378 if(in_array('T', $flags))
379 $this->mTitleDisplay = $disp;
380 else
381 $text .= $disp;
383 if(in_array('A', $flags)) {
384 /* modify the conversion table for this session*/
386 /* fill in the missing variants, if any,
387 with fallbacks */
388 foreach($this->mVariants as $v) {
389 if(!array_key_exists($v, $carray)) {
390 $vf = $this->getVariantFallback($v);
391 if(array_key_exists($vf, $carray))
392 $carray[$v] = $carray[$vf];
396 foreach($this->mVariants as $vfrom) {
397 if(!array_key_exists($vfrom, $carray))
398 continue;
399 foreach($this->mVariants as $vto) {
400 if($vfrom == $vto)
401 continue;
402 if(!array_key_exists($vto, $carray))
403 continue;
404 $this->mTables[$vto][$carray[$vfrom]] = $carray[$vto];
408 if ( $this->mUseFss ) {
409 $this->generateFssObjects();
413 else {
414 $text .= $marked[0];
416 if(array_key_exists(1, $marked))
417 $text .= $this->autoConvert($marked[1]);
420 return $text;
424 * parse the manually marked conversion rule
425 * @param string $rule the text of the rule
426 * @return array of the translation in each variant
427 * @private
429 function parseManualRule($rules, $flags=array()) {
431 $choice = explode($this->mMarkup['varsep'], $rules);
432 $carray = array();
433 if(sizeof($choice) == 1) {
434 /* a single choice */
435 foreach($this->mVariants as $v)
436 $carray[$v] = $choice[0];
438 else {
439 foreach($choice as $c) {
440 $v = explode($this->mMarkup['codesep'], $c);
441 if(sizeof($v) != 2) // syntax error, skip
442 continue;
443 $carray[trim($v[0])] = trim($v[1]);
446 return $carray;
450 * if a language supports multiple variants, it is
451 * possible that non-existing link in one variant
452 * actually exists in another variant. this function
453 * tries to find it. See e.g. LanguageZh.php
455 * @param string $link the name of the link
456 * @param mixed $nt the title object of the link
457 * @return null the input parameters may be modified upon return
458 * @access public
460 function findVariantLink( &$link, &$nt ) {
461 global $wgDisableLangConversion;
462 $pref = $this->getPreferredVariant();
463 $ns=0;
464 if(is_object($nt))
465 $ns = $nt->getNamespace();
467 $variants = $this->autoConvertToAllVariants($link);
468 if($variants == false) //give up
469 return;
470 foreach( $variants as $v ) {
471 $varnt = Title::newFromText( $v, $ns );
472 if( $varnt && $varnt->getArticleID() > 0 ) {
473 $nt = $varnt;
474 if( !$wgDisableLangConversion )
475 $link = $v;
476 break;
482 * returns language specific hash options
484 * @access public
486 function getExtraHashOptions() {
487 $variant = $this->getPreferredVariant();
488 return '!' . $variant ;
492 * get title text as defined in the body of the article text
494 * @access public
496 function getParsedTitle() {
497 return $this->mTitleDisplay;
501 * a write lock to the cache
503 * @private
505 function lockCache() {
506 global $wgMemc;
507 $success = false;
508 for($i=0; $i<30; $i++) {
509 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
510 break;
511 sleep(1);
513 return $success;
517 * unlock cache
519 * @private
521 function unlockCache() {
522 global $wgMemc;
523 $wgMemc->delete($this->mCacheKey . "lock");
528 * Load default conversion tables
529 * This method must be implemented in derived class
531 * @private
533 function loadDefaultTables() {
534 $name = get_class($this);
535 wfDie("Must implement loadDefaultTables() method in class $name");
539 * load conversion tables either from the cache or the disk
540 * @private
542 function loadTables($fromcache=true) {
543 global $wgMemc;
544 if( $this->mTablesLoaded )
545 return;
546 $this->mTablesLoaded = true;
547 $this->mTables = false;
548 if($fromcache) {
549 $this->mTables = $wgMemc->get( $this->mCacheKey );
551 if ( !$this->mTables ) {
552 // not in cache, or we need a fresh reload.
553 // we will first load the default tables
554 // then update them using things in MediaWiki:Zhconversiontable/*
555 global $wgMessageCache;
556 $this->loadDefaultTables();
557 foreach($this->mVariants as $var) {
558 $cached = $this->parseCachedTable($var);
559 $this->mTables[$var] = array_merge($this->mTables[$var], $cached);
562 $this->postLoadTables();
564 if($this->lockCache()) {
565 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
566 $this->unlockCache();
569 if ( $this->mUseFss ) {
570 $this->generateFssObjects();
575 * Generate FSS objects. The FSS extension must be available.
577 function generateFssObjects() {
578 foreach ( $this->mTables as $variant => $table ) {
579 $this->mFssObjects[$variant] = fss_prep_replace( $table );
584 * Hook for post processig after conversion tables are loaded
587 function postLoadTables() {}
590 * Reload the conversion tables
592 * @private
594 function reloadTables() {
595 if($this->mTables)
596 unset($this->mTables);
597 $this->mTablesLoaded = false;
598 $this->loadTables(false);
603 * parse the conversion table stored in the cache
605 * the tables should be in blocks of the following form:
607 * -{
608 * word => word ;
609 * word => word ;
610 * ...
611 * }-
613 * to make the tables more manageable, subpages are allowed
614 * and will be parsed recursively if $recursive=true
616 * @private
618 function parseCachedTable($code, $subpage='', $recursive=true) {
619 global $wgMessageCache;
620 static $parsed = array();
622 if(!is_object($wgMessageCache))
623 return array();
625 $key = 'Conversiontable/'.$code;
626 if($subpage)
627 $key .= '/' . $subpage;
629 if(array_key_exists($key, $parsed))
630 return array();
633 $txt = $wgMessageCache->get( $key, true, true, true );
635 // get all subpage links of the form
636 // [[MediaWiki:conversiontable/zh-xx/...|...]]
637 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
638 $subs = explode('[[', $txt);
639 $sublinks = array();
640 foreach( $subs as $sub ) {
641 $link = explode(']]', $sub, 2);
642 if(count($link) != 2)
643 continue;
644 $b = explode('|', $link[0]);
645 $b = explode('/', trim($b[0]), 3);
646 if(count($b)==3)
647 $sublink = $b[2];
648 else
649 $sublink = '';
651 if($b[0] == $linkhead && $b[1] == $code) {
652 $sublinks[] = $sublink;
657 // parse the mappings in this page
658 $blocks = explode($this->mMarkup['begin'], $txt);
659 array_shift($blocks);
660 $ret = array();
661 foreach($blocks as $block) {
662 $mappings = explode($this->mMarkup['end'], $block, 2);
663 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
664 $table = explode( ';', $stripped );
665 foreach( $table as $t ) {
666 $m = explode( '=>', $t );
667 if( count( $m ) != 2)
668 continue;
669 // trim any trailling comments starting with '//'
670 $tt = explode('//', $m[1], 2);
671 $ret[trim($m[0])] = trim($tt[0]);
674 $parsed[$key] = true;
677 // recursively parse the subpages
678 if($recursive) {
679 foreach($sublinks as $link) {
680 $s = $this->parseCachedTable($code, $link, $recursive);
681 $ret = array_merge($ret, $s);
685 if ($this->mUcfirst) {
686 foreach ($ret as $k => $v) {
687 $ret[Language::ucfirst($k)] = Language::ucfirst($v);
690 return $ret;
694 * Enclose a string with the "no conversion" tag. This is used by
695 * various functions in the Parser
697 * @param string $text text to be tagged for no conversion
698 * @return string the tagged text
700 function markNoConversion($text, $noParse=false) {
701 # don't mark if already marked
702 if(strpos($text, $this->mMarkup['begin']) ||
703 strpos($text, $this->mMarkup['end']))
704 return $text;
706 $ret = $this->mMarkup['begin'] . $text . $this->mMarkup['end'];
707 return $ret;
711 * convert the sorting key for category links. this should make different
712 * keys that are variants of each other map to the same key
714 function convertCategoryKey( $key ) {
715 return $key;
718 * hook to refresh the cache of conversion tables when
719 * MediaWiki:conversiontable* is updated
720 * @private
722 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
723 $titleobj = $article->getTitle();
724 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
726 global $wgContLang; // should be an LanguageZh.
727 if(get_class($wgContLang) != 'languagezh')
728 return true;
730 $title = $titleobj->getDBkey();
731 $t = explode('/', $title, 3);
732 $c = count($t);
733 if( $c > 1 && $t[0] == 'Conversiontable' ) {
734 if(in_array($t[1], $this->mVariants)) {
735 $this->reloadTables();
739 return true;
742 function setNoTitleConvert(){
743 $this->mNoTitleConvert = true;