6 * @author Zhengzhu Feng <zhengzhu@gmail.com>
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
10 class LanguageConverter
{
11 var $mPreferredVariant='';
12 var $mMainLanguageCode;
13 var $mVariants, $mVariantFallbacks;
14 var $mTablesLoaded = false;
16 var $mTitleDisplay='';
17 var $mDoTitleConvert=true, $mDoContentConvert=true;
18 var $mTitleFromFlag = false;
23 var $mUcfirst = false;
27 * @param string $maincode the main language code of this language
28 * @param array $variants the supported variants of this language
29 * @param array $variantfallback the fallback language of each variant
30 * @param array $markup array defining the markup used for manual conversion
31 * @param array $flags array defining the custom strings that maps to the flags
34 function __construct($langobj, $maincode,
36 $variantfallbacks=array(),
39 global $wgLegalTitleChars;
40 $this->mLangObj
= $langobj;
41 $this->mMainLanguageCode
= $maincode;
42 $this->mVariants
= $variants;
43 $this->mVariantFallbacks
= $variantfallbacks;
44 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
45 $m = array('begin'=>'-{', 'flagsep'=>'|', 'codesep'=>':',
46 'varsep'=>';', 'end'=>'}-');
47 $this->mMarkup
= array_merge($m, $markup);
48 $f = array('A'=>'A', 'T'=>'T', 'R' => 'R');
49 $this->mFlags
= array_merge($f, $flags);
55 function getVariants() {
56 return $this->mVariants
;
60 * in case some variant is not defined in the markup, we need
61 * to have some fallback. for example, in zh, normally people
62 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
63 * when zh-sg is preferred but not defined, we will pick zh-cn
64 * in this case. right now this is only used by zh.
66 * @param string $v the language code of the variant
67 * @return string the code of the fallback language or false if there is no fallback
70 function getVariantFallback($v) {
71 return $this->mVariantFallbacks
[$v];
76 * get preferred language variants.
77 * @param boolean $fromUser Get it from $wgUser's preferences
78 * @return string the preferred language code
81 function getPreferredVariant( $fromUser = true ) {
82 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
84 if($this->mPreferredVariant
)
85 return $this->mPreferredVariant
;
87 // see if the preference is set in the request
88 $req = $wgRequest->getText( 'variant' );
89 if( in_array( $req, $this->mVariants
) ) {
90 $this->mPreferredVariant
= $req;
94 // check the syntax /code/ArticleTitle
95 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
96 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
97 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
98 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
99 if(in_array($scriptBase,$this->mVariants
)){
100 $this->mPreferredVariant
= $scriptBase;
101 return $this->mPreferredVariant
;
105 // get language variant preference from logged in users
106 // Don't call this on stub objects because that causes infinite
107 // recursion during initialisation
108 if( $fromUser && $wgUser->isLoggedIn() ) {
109 $this->mPreferredVariant
= $wgUser->getOption('variant');
110 return $this->mPreferredVariant
;
113 // see if default variant is globaly set
114 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
115 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
116 return $this->mPreferredVariant
;
119 # FIXME rewrite code for parsing http header. The current code
120 # is written specific for detecting zh- variants
121 if( !$this->mPreferredVariant
) {
122 // see if some supported language variant is set in the
123 // http header, but we don't set the mPreferredVariant
124 // variable in case this is called before the user's
125 // preference is loaded
126 $pv=$this->mMainLanguageCode
;
127 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
128 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
129 $zh = strstr($header, $pv.'-');
131 $pv = substr($zh,0,5);
134 // don't try to return bad variant
135 if(in_array( $pv, $this->mVariants
))
139 return $this->mMainLanguageCode
;
144 * dictionary-based conversion
146 * @param string $text the text to be converted
147 * @param string $toVariant the target language code
148 * @return string the converted text
151 function autoConvert($text, $toVariant=false) {
152 $fname="LanguageConverter::autoConvert";
154 wfProfileIn( $fname );
156 if(!$this->mTablesLoaded
)
160 $toVariant = $this->getPreferredVariant();
161 if(!in_array($toVariant, $this->mVariants
))
164 /* we convert everything except:
165 1. html markups (anything between < and >)
167 3. place holders created by the parser
170 if (isset($wgParser))
171 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
175 // this one is needed when the text is inside an html markup
176 $htmlfix = '|<[^>]+$|^[^<>]*>';
178 // disable convert to variants between <code></code> tags
179 $codefix = '<code>.+?<\/code>|';
180 // disable convertsion of <script type="text/javascript"> ... </script>
181 $scriptfix = '<script.*?>.*?<\/script>|';
183 $reg = '/'.$codefix . $scriptfix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
185 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
187 $m = array_shift($matches);
189 $ret = $this->translate($m[0], $toVariant);
190 $mstart = $m[1]+
strlen($m[0]);
191 foreach($matches as $m) {
192 $ret .= substr($text, $mstart, $m[1]-$mstart);
193 $ret .= $this->translate($m[0], $toVariant);
194 $mstart = $m[1] +
strlen($m[0]);
196 wfProfileOut( $fname );
201 * Translate a string to a variant
202 * Doesn't process markup or do any of that other stuff, for that use convert()
204 * @param string $text Text to convert
205 * @param string $variant Variant language code
206 * @return string Translated text
208 function translate( $text, $variant ) {
209 wfProfileIn( __METHOD__
);
210 if( !$this->mTablesLoaded
)
212 $text = $this->mTables
[$variant]->replace( $text );
213 wfProfileOut( __METHOD__
);
218 * convert text to all supported variants
220 * @param string $text the text to be converted
221 * @return array of string
224 function autoConvertToAllVariants($text) {
225 $fname="LanguageConverter::autoConvertToAllVariants";
226 wfProfileIn( $fname );
227 if( !$this->mTablesLoaded
)
231 foreach($this->mVariants
as $variant) {
232 $ret[$variant] = $this->translate($text, $variant);
235 wfProfileOut( $fname );
240 * convert link text to all supported variants
242 * @param string $text the text to be converted
243 * @return array of string
246 function convertLinkToAllVariants($text) {
247 if( !$this->mTablesLoaded
)
251 $tarray = explode($this->mMarkup
['begin'], $text);
252 $tfirst = array_shift($tarray);
254 foreach($this->mVariants
as $variant)
255 $ret[$variant] = $this->translate($tfirst,$variant);
257 foreach($tarray as $txt) {
258 $marked = explode($this->mMarkup
['end'], $txt, 2);
260 foreach($this->mVariants
as $variant){
261 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
262 if(array_key_exists(1, $marked))
263 $ret[$variant] .= $this->translate($marked[1],$variant);
273 * Convert text using a parser object for context
275 function parserConvert( $text, &$parser ) {
276 global $wgDisableLangConversion;
277 /* don't do anything if this is the conversion table */
278 if ( $parser->mTitle
->getNamespace() == NS_MEDIAWIKI
&&
279 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
284 if($wgDisableLangConversion)
287 $text = $this->convert( $text );
288 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
293 * Parse flags with syntax -{FLAG| ... }-
296 function parseFlags($marked){
299 // process flag only if the flag is valid
300 if(strlen($marked) < 2 ||
!(in_array($marked[0],$this->mFlags
) && $marked[1]=='|' ) )
301 return array($marked,array());
303 $tt = explode($this->mMarkup
['flagsep'], $marked, 2);
305 if(sizeof($tt) == 2) {
306 $f = explode($this->mMarkup
['varsep'], $tt[0]);
309 if(array_key_exists($ff, $this->mFlags
) &&
310 !array_key_exists($this->mFlags
[$ff], $flags))
311 $flags[] = $this->mFlags
[$ff];
318 if( !in_array('R',$flags) ){
319 //FIXME: may cause trouble here...
320 //strip since it interferes with the parsing, plus,
321 //all spaces should be stripped in this tag anyway.
322 $rules = str_replace(' ', '', $rules);
325 return array($rules,$flags);
329 * convert text to different variants of a language. the automatic
330 * conversion is done in autoConvert(). here we parse the text
331 * marked with -{}-, which specifies special conversions of the
332 * text that can not be accomplished in autoConvert()
334 * syntax of the markup:
335 * -{code1:text1;code2:text2;...}- or
336 * -{text}- in which case no conversion should take place for text
338 * @param string $text text to be converted
339 * @param bool $isTitle whether this conversion is for the article title
340 * @return string converted text
343 function convert( $text , $isTitle=false) {
344 $mw =& MagicWord
::get( 'notitleconvert' );
345 if( $mw->matchAndRemove( $text ) )
346 $this->mDoTitleConvert
= false;
348 $mw =& MagicWord
::get( 'nocontentconvert' );
349 if( $mw->matchAndRemove( $text ) ) {
350 $this->mDoContentConvert
= false;
353 // no conversion if redirecting
354 $mw =& MagicWord
::get( 'redirect' );
355 if( $mw->matchStart( $text ))
360 // use the title from the T flag if any
361 if($this->mTitleFromFlag
){
362 $this->mTitleFromFlag
= false;
363 return $this->mTitleDisplay
;
366 // check for __NOTC__ tag
367 if( !$this->mDoTitleConvert
) {
368 $this->mTitleDisplay
= $text;
373 $isredir = $wgRequest->getText( 'redirect', 'yes' );
374 $action = $wgRequest->getText( 'action' );
375 if ( $isredir == 'no' ||
$action == 'edit' ) {
379 $this->mTitleDisplay
= $this->convert($text);
380 return $this->mTitleDisplay
;
384 $plang = $this->getPreferredVariant();
385 if( isset( $this->mVariantFallbacks
[$plang] ) ) {
386 $fallback = $this->mVariantFallbacks
[$plang];
388 $fallback = $this->mMainLanguageCode
;
391 $tarray = explode($this->mMarkup
['begin'], $text);
392 $tfirst = array_shift($tarray);
393 if($this->mDoContentConvert
)
394 $text = $this->autoConvert($tfirst);
397 foreach($tarray as $txt) {
398 $marked = explode($this->mMarkup
['end'], $txt, 2);
400 // strip the flags from syntax like -{T| ... }-
401 list($rules,$flags) = $this->parseFlags($marked[0]);
403 // proces R flag: output raw content of -{ ... }-
404 if( in_array('R',$flags) ){
406 } else if( $this->mDoContentConvert
){
407 // parse the contents -{ ... }-
408 $carray = $this->parseManualRule($rules, $flags);
411 if(array_key_exists($plang, $carray))
412 $disp = $carray[$plang];
413 else if(array_key_exists($fallback, $carray))
414 $disp = $carray[$fallback];
416 // if we don't do content convert, still strip the -{}- tags
422 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
423 if(in_array('T', $flags)){
424 $this->mTitleFromFlag
= true;
425 $this->mTitleDisplay
= $disp;
430 // use syntax -{A|zh:WordZh;zh-tw:WordTw}- to introduce a custom mapping between
431 // words WordZh and WordTw in the whole text
432 if(in_array('A', $flags)) {
434 /* fill in the missing variants, if any,
436 foreach($this->mVariants
as $v) {
437 if(!array_key_exists($v, $carray)) {
438 $vf = $this->getVariantFallback($v);
439 if(array_key_exists($vf, $carray))
440 $carray[$v] = $carray[$vf];
444 foreach($this->mVariants
as $vfrom) {
445 if(!array_key_exists($vfrom, $carray))
447 foreach($this->mVariants
as $vto) {
450 if(!array_key_exists($vto, $carray))
452 $this->mTables
[$vto]->setPair($carray[$vfrom], $carray[$vto]);
460 if(array_key_exists(1, $marked)){
461 if( $this->mDoContentConvert
)
462 $text .= $this->autoConvert($marked[1]);
472 * parse the manually marked conversion rule
473 * @param string $rule the text of the rule
474 * @return array of the translation in each variant
477 function parseManualRule($rules, $flags=array()) {
479 $choice = explode($this->mMarkup
['varsep'], $rules);
481 if(sizeof($choice) == 1) {
482 /* a single choice */
483 foreach($this->mVariants
as $v)
484 $carray[$v] = $choice[0];
487 foreach($choice as $c) {
488 $v = explode($this->mMarkup
['codesep'], $c);
489 if(sizeof($v) != 2) // syntax error, skip
491 $carray[trim($v[0])] = trim($v[1]);
498 * if a language supports multiple variants, it is
499 * possible that non-existing link in one variant
500 * actually exists in another variant. this function
501 * tries to find it. See e.g. LanguageZh.php
503 * @param string $link the name of the link
504 * @param mixed $nt the title object of the link
505 * @return null the input parameters may be modified upon return
508 function findVariantLink( &$link, &$nt ) {
509 global $wgDisableLangConversion;
510 $linkBatch = new LinkBatch();
515 $ns = $nt->getNamespace();
517 $variants = $this->autoConvertToAllVariants($link);
518 if($variants == false) //give up
523 foreach( $variants as $v ) {
525 $varnt = Title
::newFromText( $v, $ns );
526 if(!is_null($varnt)){
527 $linkBatch->addObj($varnt);
533 // fetch all variants in single query
534 $linkBatch->execute();
536 foreach( $titles as $varnt ) {
537 if( $varnt->getArticleID() > 0 ) {
539 if( !$wgDisableLangConversion )
547 * returns language specific hash options
551 function getExtraHashOptions() {
552 $variant = $this->getPreferredVariant();
553 return '!' . $variant ;
557 * get title text as defined in the body of the article text
561 function getParsedTitle() {
562 return $this->mTitleDisplay
;
566 * a write lock to the cache
570 function lockCache() {
573 for($i=0; $i<30; $i++
) {
574 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
586 function unlockCache() {
588 $wgMemc->delete($this->mCacheKey
. "lock");
593 * Load default conversion tables
594 * This method must be implemented in derived class
598 function loadDefaultTables() {
599 $name = get_class($this);
600 wfDie("Must implement loadDefaultTables() method in class $name");
604 * load conversion tables either from the cache or the disk
607 function loadTables($fromcache=true) {
609 if( $this->mTablesLoaded
)
611 wfProfileIn( __METHOD__
);
612 $this->mTablesLoaded
= true;
613 $this->mTables
= false;
615 wfProfileIn( __METHOD__
.'-cache' );
616 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
617 wfProfileOut( __METHOD__
.'-cache' );
619 if ( !$this->mTables ||
!isset( $this->mTables
['VERSION 2'] ) ) {
620 wfProfileIn( __METHOD__
.'-recache' );
621 // not in cache, or we need a fresh reload.
622 // we will first load the default tables
623 // then update them using things in MediaWiki:Zhconversiontable/*
624 global $wgMessageCache;
625 $this->loadDefaultTables();
626 foreach($this->mVariants
as $var) {
627 $cached = $this->parseCachedTable($var);
628 $this->mTables
[$var]->mergeArray($cached);
631 $this->postLoadTables();
632 $this->mTables
['VERSION 2'] = true;
634 if($this->lockCache()) {
635 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
636 $this->unlockCache();
638 wfProfileOut( __METHOD__
.'-recache' );
640 wfProfileOut( __METHOD__
);
644 * Hook for post processig after conversion tables are loaded
647 function postLoadTables() {}
650 * Reload the conversion tables
654 function reloadTables() {
656 unset($this->mTables
);
657 $this->mTablesLoaded
= false;
658 $this->loadTables(false);
663 * parse the conversion table stored in the cache
665 * the tables should be in blocks of the following form:
673 * to make the tables more manageable, subpages are allowed
674 * and will be parsed recursively if $recursive=true
678 function parseCachedTable($code, $subpage='', $recursive=true) {
679 global $wgMessageCache;
680 static $parsed = array();
682 if(!is_object($wgMessageCache))
685 $key = 'Conversiontable/'.$code;
687 $key .= '/' . $subpage;
689 if(array_key_exists($key, $parsed))
693 $txt = $wgMessageCache->get( $key, true, true, true );
695 // get all subpage links of the form
696 // [[MediaWiki:conversiontable/zh-xx/...|...]]
697 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
698 $subs = explode('[[', $txt);
700 foreach( $subs as $sub ) {
701 $link = explode(']]', $sub, 2);
702 if(count($link) != 2)
704 $b = explode('|', $link[0]);
705 $b = explode('/', trim($b[0]), 3);
711 if($b[0] == $linkhead && $b[1] == $code) {
712 $sublinks[] = $sublink;
717 // parse the mappings in this page
718 $blocks = explode($this->mMarkup
['begin'], $txt);
719 array_shift($blocks);
721 foreach($blocks as $block) {
722 $mappings = explode($this->mMarkup
['end'], $block, 2);
723 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
724 $table = explode( ';', $stripped );
725 foreach( $table as $t ) {
726 $m = explode( '=>', $t );
727 if( count( $m ) != 2)
729 // trim any trailling comments starting with '//'
730 $tt = explode('//', $m[1], 2);
731 $ret[trim($m[0])] = trim($tt[0]);
734 $parsed[$key] = true;
737 // recursively parse the subpages
739 foreach($sublinks as $link) {
740 $s = $this->parseCachedTable($code, $link, $recursive);
741 $ret = array_merge($ret, $s);
745 if ($this->mUcfirst
) {
746 foreach ($ret as $k => $v) {
747 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
754 * Enclose a string with the "no conversion" tag. This is used by
755 * various functions in the Parser
757 * @param string $text text to be tagged for no conversion
758 * @return string the tagged text
760 function markNoConversion($text, $noParse=false) {
761 # don't mark if already marked
762 if(strpos($text, $this->mMarkup
['begin']) ||
763 strpos($text, $this->mMarkup
['end']))
766 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
771 * convert the sorting key for category links. this should make different
772 * keys that are variants of each other map to the same key
774 function convertCategoryKey( $key ) {
778 * hook to refresh the cache of conversion tables when
779 * MediaWiki:conversiontable* is updated
782 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
783 $titleobj = $article->getTitle();
784 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
786 global $wgContLang; // should be an LanguageZh.
787 if(get_class($wgContLang) != 'languagezh')
790 $title = $titleobj->getDBkey();
791 $t = explode('/', $title, 3);
793 if( $c > 1 && $t[0] == 'Conversiontable' ) {
794 if(in_array($t[1], $this->mVariants
)) {
795 $this->reloadTables();
803 * Armour rendered math against conversion
804 * Wrap math into rawoutput -{R| math }- syntax
806 function armourMath($text){
807 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];