5 * @author Zhengzhu Feng <zhengzhu@gmail.com>
6 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
9 class LanguageConverter
{
10 var $mPreferredVariant='';
11 var $mMainLanguageCode;
12 var $mVariants, $mVariantFallbacks;
13 var $mTablesLoaded = false;
15 var $mTitleDisplay='';
16 var $mDoTitleConvert=true, $mDoContentConvert=true;
17 var $mTitleFromFlag = false;
22 var $mUcfirst = false;
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
33 function __construct($langobj, $maincode,
35 $variantfallbacks=array(),
38 $this->mLangObj
= $langobj;
39 $this->mMainLanguageCode
= $maincode;
40 $this->mVariants
= $variants;
41 $this->mVariantFallbacks
= $variantfallbacks;
42 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
43 $m = array('begin'=>'-{', 'flagsep'=>'|', 'codesep'=>':',
44 'varsep'=>';', 'end'=>'}-');
45 $this->mMarkup
= array_merge($m, $markup);
46 $f = array('A'=>'A', 'T'=>'T', 'R' => 'R');
47 $this->mFlags
= array_merge($f, $flags);
53 function getVariants() {
54 return $this->mVariants
;
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.
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
68 function getVariantFallback($v) {
69 return $this->mVariantFallbacks
[$v];
74 * get preferred language variants.
75 * @param boolean $fromUser Get it from $wgUser's preferences
76 * @return string the preferred language code
79 function getPreferredVariant( $fromUser = true ) {
80 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
82 if($this->mPreferredVariant
)
83 return $this->mPreferredVariant
;
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;
92 // check the syntax /code/ArticleTitle
93 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
94 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
95 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
96 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
97 if(in_array($scriptBase,$this->mVariants
)){
98 $this->mPreferredVariant
= $scriptBase;
99 return $this->mPreferredVariant
;
103 // get language variant preference from logged in users
104 // Don't call this on stub objects because that causes infinite
105 // recursion during initialisation
106 if( $fromUser && $wgUser->isLoggedIn() ) {
107 $this->mPreferredVariant
= $wgUser->getOption('variant');
108 return $this->mPreferredVariant
;
111 // see if default variant is globaly set
112 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
113 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
114 return $this->mPreferredVariant
;
117 # FIXME rewrite code for parsing http header. The current code
118 # is written specific for detecting zh- variants
119 if( !$this->mPreferredVariant
) {
120 // see if some supported language variant is set in the
121 // http header, but we don't set the mPreferredVariant
122 // variable in case this is called before the user's
123 // preference is loaded
124 $pv=$this->mMainLanguageCode
;
125 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
126 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
127 $zh = strstr($header, $pv.'-');
129 $pv = substr($zh,0,5);
132 // don't try to return bad variant
133 if(in_array( $pv, $this->mVariants
))
137 return $this->mMainLanguageCode
;
142 * dictionary-based conversion
144 * @param string $text the text to be converted
145 * @param string $toVariant the target language code
146 * @return string the converted text
149 function autoConvert($text, $toVariant=false) {
150 $fname="LanguageConverter::autoConvert";
152 wfProfileIn( $fname );
154 if(!$this->mTablesLoaded
)
158 $toVariant = $this->getPreferredVariant();
159 if(!in_array($toVariant, $this->mVariants
))
162 /* we convert everything except:
163 1. html markups (anything between < and >)
165 3. place holders created by the parser
168 if (isset($wgParser))
169 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
173 // this one is needed when the text is inside an html markup
174 $htmlfix = '|<[^>]+$|^[^<>]*>';
176 // disable convert to variants between <code></code> tags
177 $codefix = '<code>.+?<\/code>|';
178 // disable convertsion of <script type="text/javascript"> ... </script>
179 $scriptfix = '<script.*?>.*?<\/script>|';
181 $reg = '/'.$codefix . $scriptfix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
183 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
185 $m = array_shift($matches);
187 $ret = $this->translate($m[0], $toVariant);
188 $mstart = $m[1]+
strlen($m[0]);
189 foreach($matches as $m) {
190 $ret .= substr($text, $mstart, $m[1]-$mstart);
191 $ret .= $this->translate($m[0], $toVariant);
192 $mstart = $m[1] +
strlen($m[0]);
194 wfProfileOut( $fname );
199 * Translate a string to a variant
200 * Doesn't process markup or do any of that other stuff, for that use convert()
202 * @param string $text Text to convert
203 * @param string $variant Variant language code
204 * @return string Translated text
206 function translate( $text, $variant ) {
207 wfProfileIn( __METHOD__
);
208 if( !$this->mTablesLoaded
)
210 $text = $this->mTables
[$variant]->replace( $text );
211 wfProfileOut( __METHOD__
);
216 * convert text to all supported variants
218 * @param string $text the text to be converted
219 * @return array of string
222 function autoConvertToAllVariants($text) {
223 $fname="LanguageConverter::autoConvertToAllVariants";
224 wfProfileIn( $fname );
225 if( !$this->mTablesLoaded
)
229 foreach($this->mVariants
as $variant) {
230 $ret[$variant] = $this->translate($text, $variant);
233 wfProfileOut( $fname );
238 * convert link text to all supported variants
240 * @param string $text the text to be converted
241 * @return array of string
244 function convertLinkToAllVariants($text) {
245 if( !$this->mTablesLoaded
)
249 $tarray = explode($this->mMarkup
['begin'], $text);
250 $tfirst = array_shift($tarray);
252 foreach($this->mVariants
as $variant)
253 $ret[$variant] = $this->translate($tfirst,$variant);
255 foreach($tarray as $txt) {
256 $marked = explode($this->mMarkup
['end'], $txt, 2);
258 foreach($this->mVariants
as $variant){
259 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
260 if(array_key_exists(1, $marked))
261 $ret[$variant] .= $this->translate($marked[1],$variant);
271 * Convert text using a parser object for context
273 function parserConvert( $text, &$parser ) {
274 global $wgDisableLangConversion;
275 /* don't do anything if this is the conversion table */
276 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
277 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
282 if($wgDisableLangConversion)
285 $text = $this->convert( $text );
286 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
291 * Parse flags with syntax -{FLAG| ... }-
294 function parseFlags($marked){
297 // process flag only if the flag is valid
298 if(strlen($marked) < 2 ||
!(in_array($marked[0],$this->mFlags
) && $marked[1]=='|' ) )
299 return array($marked,array());
301 $tt = explode($this->mMarkup
['flagsep'], $marked, 2);
303 if(sizeof($tt) == 2) {
304 $f = explode($this->mMarkup
['varsep'], $tt[0]);
307 if(array_key_exists($ff, $this->mFlags
) &&
308 !array_key_exists($this->mFlags
[$ff], $flags))
309 $flags[] = $this->mFlags
[$ff];
316 if( !in_array('R',$flags) ){
317 //FIXME: may cause trouble here...
318 //strip since it interferes with the parsing, plus,
319 //all spaces should be stripped in this tag anyway.
320 $rules = str_replace(' ', '', $rules);
323 return array($rules,$flags);
327 * convert text to different variants of a language. the automatic
328 * conversion is done in autoConvert(). here we parse the text
329 * marked with -{}-, which specifies special conversions of the
330 * text that can not be accomplished in autoConvert()
332 * syntax of the markup:
333 * -{code1:text1;code2:text2;...}- or
334 * -{text}- in which case no conversion should take place for text
336 * @param string $text text to be converted
337 * @param bool $isTitle whether this conversion is for the article title
338 * @return string converted text
341 function convert( $text , $isTitle=false) {
342 $mw =& MagicWord
::get( 'notitleconvert' );
343 if( $mw->matchAndRemove( $text ) )
344 $this->mDoTitleConvert
= false;
346 $mw =& MagicWord
::get( 'nocontentconvert' );
347 if( $mw->matchAndRemove( $text ) ) {
348 $this->mDoContentConvert
= false;
351 // no conversion if redirecting
352 $mw =& MagicWord
::get( 'redirect' );
353 if( $mw->matchStart( $text ))
358 // use the title from the T flag if any
359 if($this->mTitleFromFlag
){
360 $this->mTitleFromFlag
= false;
361 return $this->mTitleDisplay
;
364 // check for __NOTC__ tag
365 if( !$this->mDoTitleConvert
) {
366 $this->mTitleDisplay
= $text;
371 $isredir = $wgRequest->getText( 'redirect', 'yes' );
372 $action = $wgRequest->getText( 'action' );
373 if ( $isredir == 'no' ||
$action == 'edit' ) {
377 $this->mTitleDisplay
= $this->convert($text);
378 return $this->mTitleDisplay
;
382 $plang = $this->getPreferredVariant();
383 if( isset( $this->mVariantFallbacks
[$plang] ) ) {
384 $fallback = $this->mVariantFallbacks
[$plang];
386 $fallback = $this->mMainLanguageCode
;
389 $tarray = explode($this->mMarkup
['begin'], $text);
390 $tfirst = array_shift($tarray);
391 if($this->mDoContentConvert
)
392 $text = $this->autoConvert($tfirst);
395 foreach($tarray as $txt) {
396 $marked = explode($this->mMarkup
['end'], $txt, 2);
398 // strip the flags from syntax like -{T| ... }-
399 list($rules,$flags) = $this->parseFlags($marked[0]);
401 // proces R flag: output raw content of -{ ... }-
402 if( in_array('R',$flags) ){
404 } else if( $this->mDoContentConvert
){
405 // parse the contents -{ ... }-
406 $carray = $this->parseManualRule($rules, $flags);
409 if(array_key_exists($plang, $carray)) {
410 $disp = $carray[$plang];
411 } else if(array_key_exists($fallback, $carray)) {
412 $disp = $carray[$fallback];
415 // if we don't do content convert, still strip the -{}- tags
421 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
422 if(in_array('T', $flags)){
423 $this->mTitleFromFlag
= true;
424 $this->mTitleDisplay
= $disp;
429 // use syntax -{A|zh:WordZh;zh-tw:WordTw}- to introduce a custom mapping between
430 // words WordZh and WordTw in the whole text
431 if(in_array('A', $flags)) {
433 /* fill in the missing variants, if any,
435 foreach($this->mVariants
as $v) {
436 if(!array_key_exists($v, $carray)) {
437 $vf = $this->getVariantFallback($v);
438 if(array_key_exists($vf, $carray))
439 $carray[$v] = $carray[$vf];
443 foreach($this->mVariants
as $vfrom) {
444 if(!array_key_exists($vfrom, $carray))
446 foreach($this->mVariants
as $vto) {
449 if(!array_key_exists($vto, $carray))
451 $this->mTables
[$vto]->setPair($carray[$vfrom], $carray[$vto]);
459 if(array_key_exists(1, $marked)){
460 if( $this->mDoContentConvert
)
461 $text .= $this->autoConvert($marked[1]);
471 * parse the manually marked conversion rule
472 * @param string $rule the text of the rule
473 * @return array of the translation in each variant
476 function parseManualRule($rules, $flags=array()) {
478 $choice = explode($this->mMarkup
['varsep'], $rules);
480 if(sizeof($choice) == 1) {
481 /* a single choice */
482 foreach($this->mVariants
as $v)
483 $carray[$v] = $choice[0];
486 foreach($choice as $c) {
487 $v = explode($this->mMarkup
['codesep'], $c);
488 if(sizeof($v) != 2) // syntax error, skip
490 $carray[trim($v[0])] = trim($v[1]);
497 * if a language supports multiple variants, it is
498 * possible that non-existing link in one variant
499 * actually exists in another variant. this function
500 * tries to find it. See e.g. LanguageZh.php
502 * @param string $link the name of the link
503 * @param mixed $nt the title object of the link
504 * @return null the input parameters may be modified upon return
507 function findVariantLink( &$link, &$nt ) {
508 global $wgDisableLangConversion;
509 $linkBatch = new LinkBatch();
514 $ns = $nt->getNamespace();
516 $variants = $this->autoConvertToAllVariants($link);
517 if($variants == false) //give up
522 foreach( $variants as $v ) {
524 $varnt = Title
::newFromText( $v, $ns );
525 if(!is_null($varnt)){
526 $linkBatch->addObj($varnt);
532 // fetch all variants in single query
533 $linkBatch->execute();
535 foreach( $titles as $varnt ) {
536 if( $varnt->getArticleID() > 0 ) {
538 if( !$wgDisableLangConversion )
546 * returns language specific hash options
550 function getExtraHashOptions() {
551 $variant = $this->getPreferredVariant();
552 return '!' . $variant ;
556 * get title text as defined in the body of the article text
560 function getParsedTitle() {
561 return $this->mTitleDisplay
;
565 * a write lock to the cache
569 function lockCache() {
572 for($i=0; $i<30; $i++
) {
573 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
585 function unlockCache() {
587 $wgMemc->delete($this->mCacheKey
. "lock");
592 * Load default conversion tables
593 * This method must be implemented in derived class
597 function loadDefaultTables() {
598 $name = get_class($this);
599 wfDie("Must implement loadDefaultTables() method in class $name");
603 * load conversion tables either from the cache or the disk
606 function loadTables($fromcache=true) {
608 if( $this->mTablesLoaded
)
610 wfProfileIn( __METHOD__
);
611 $this->mTablesLoaded
= true;
612 $this->mTables
= false;
614 wfProfileIn( __METHOD__
.'-cache' );
615 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
616 wfProfileOut( __METHOD__
.'-cache' );
618 if ( !$this->mTables ||
!isset( $this->mTables
['VERSION 2'] ) ) {
619 wfProfileIn( __METHOD__
.'-recache' );
620 // not in cache, or we need a fresh reload.
621 // we will first load the default tables
622 // then update them using things in MediaWiki:Zhconversiontable/*
623 $this->loadDefaultTables();
624 foreach($this->mVariants
as $var) {
625 $cached = $this->parseCachedTable($var);
626 $this->mTables
[$var]->mergeArray($cached);
629 $this->postLoadTables();
630 $this->mTables
['VERSION 2'] = true;
632 if($this->lockCache()) {
633 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
634 $this->unlockCache();
636 wfProfileOut( __METHOD__
.'-recache' );
638 wfProfileOut( __METHOD__
);
642 * Hook for post processig after conversion tables are loaded
645 function postLoadTables() {}
648 * Reload the conversion tables
652 function reloadTables() {
654 unset($this->mTables
);
655 $this->mTablesLoaded
= false;
656 $this->loadTables(false);
661 * parse the conversion table stored in the cache
663 * the tables should be in blocks of the following form:
671 * to make the tables more manageable, subpages are allowed
672 * and will be parsed recursively if $recursive=true
676 function parseCachedTable($code, $subpage='', $recursive=true) {
677 global $wgMessageCache;
678 static $parsed = array();
680 if(!is_object($wgMessageCache))
683 $key = 'Conversiontable/'.$code;
685 $key .= '/' . $subpage;
687 if(array_key_exists($key, $parsed))
691 $txt = $wgMessageCache->get( $key, true, true, true );
693 // get all subpage links of the form
694 // [[MediaWiki:conversiontable/zh-xx/...|...]]
695 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
696 $subs = explode('[[', $txt);
698 foreach( $subs as $sub ) {
699 $link = explode(']]', $sub, 2);
700 if(count($link) != 2)
702 $b = explode('|', $link[0]);
703 $b = explode('/', trim($b[0]), 3);
709 if($b[0] == $linkhead && $b[1] == $code) {
710 $sublinks[] = $sublink;
715 // parse the mappings in this page
716 $blocks = explode($this->mMarkup
['begin'], $txt);
717 array_shift($blocks);
719 foreach($blocks as $block) {
720 $mappings = explode($this->mMarkup
['end'], $block, 2);
721 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
722 $table = explode( ';', $stripped );
723 foreach( $table as $t ) {
724 $m = explode( '=>', $t );
725 if( count( $m ) != 2)
727 // trim any trailling comments starting with '//'
728 $tt = explode('//', $m[1], 2);
729 $ret[trim($m[0])] = trim($tt[0]);
732 $parsed[$key] = true;
735 // recursively parse the subpages
737 foreach($sublinks as $link) {
738 $s = $this->parseCachedTable($code, $link, $recursive);
739 $ret = array_merge($ret, $s);
743 if ($this->mUcfirst
) {
744 foreach ($ret as $k => $v) {
745 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
752 * Enclose a string with the "no conversion" tag. This is used by
753 * various functions in the Parser
755 * @param string $text text to be tagged for no conversion
756 * @return string the tagged text
758 function markNoConversion($text, $noParse=false) {
759 # don't mark if already marked
760 if(strpos($text, $this->mMarkup
['begin']) ||
761 strpos($text, $this->mMarkup
['end']))
764 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
769 * convert the sorting key for category links. this should make different
770 * keys that are variants of each other map to the same key
772 function convertCategoryKey( $key ) {
776 * hook to refresh the cache of conversion tables when
777 * MediaWiki:conversiontable* is updated
780 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
781 $titleobj = $article->getTitle();
782 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
784 global $wgContLang; // should be an LanguageZh.
785 if(get_class($wgContLang) != 'languagezh')
788 $title = $titleobj->getDBkey();
789 $t = explode('/', $title, 3);
791 if( $c > 1 && $t[0] == 'Conversiontable' ) {
792 if(in_array($t[1], $this->mVariants
)) {
793 $this->reloadTables();
801 * Armour rendered math against conversion
802 * Wrap math into rawoutput -{R| math }- syntax
804 function armourMath($text){
805 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];