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 $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', 'R' => 'R');
48 $this->mFlags
= array_merge($f, $flags);
54 function getVariants() {
55 return $this->mVariants
;
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.
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
69 function getVariantFallback($v) {
70 return $this->mVariantFallbacks
[$v];
75 * get preferred language variants.
76 * @param boolean $fromUser Get it from $wgUser's preferences
77 * @return string the preferred language code
80 function getPreferredVariant( $fromUser = true ) {
81 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
83 if($this->mPreferredVariant
)
84 return $this->mPreferredVariant
;
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;
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
;
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
;
112 // see if default variant is globaly set
113 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
114 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
115 return $this->mPreferredVariant
;
118 # FIXME rewrite code for parsing http header. The current code
119 # is written specific for detecting zh- variants
120 if( !$this->mPreferredVariant
) {
121 // see if some supported language variant is set in the
122 // http header, but we don't set the mPreferredVariant
123 // variable in case this is called before the user's
124 // preference is loaded
125 $pv=$this->mMainLanguageCode
;
126 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
127 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
128 $zh = strstr($header, $pv.'-');
130 $pv = substr($zh,0,5);
133 // don't try to return bad variant
134 if(in_array( $pv, $this->mVariants
))
138 return $this->mMainLanguageCode
;
143 * dictionary-based conversion
145 * @param string $text the text to be converted
146 * @param string $toVariant the target language code
147 * @return string the converted text
150 function autoConvert($text, $toVariant=false) {
151 $fname="LanguageConverter::autoConvert";
153 wfProfileIn( $fname );
155 if(!$this->mTablesLoaded
)
159 $toVariant = $this->getPreferredVariant();
160 if(!in_array($toVariant, $this->mVariants
))
163 /* we convert everything except:
164 1. html markups (anything between < and >)
166 3. place holders created by the parser
169 if (isset($wgParser))
170 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
174 // this one is needed when the text is inside an html markup
175 $htmlfix = '|<[^>]+$|^[^<>]*>';
177 // disable convert to variants between <code></code> tags
178 $codefix = '<code>.+?<\/code>|';
179 // disable convertsion of <script type="text/javascript"> ... </script>
180 $scriptfix = '<script.*?>.*?<\/script>|';
182 $reg = '/'.$codefix . $scriptfix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
184 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
186 $m = array_shift($matches);
188 $ret = $this->translate($m[0], $toVariant);
189 $mstart = $m[1]+
strlen($m[0]);
190 foreach($matches as $m) {
191 $ret .= substr($text, $mstart, $m[1]-$mstart);
192 $ret .= $this->translate($m[0], $toVariant);
193 $mstart = $m[1] +
strlen($m[0]);
195 wfProfileOut( $fname );
200 * Translate a string to a variant
201 * Doesn't process markup or do any of that other stuff, for that use convert()
203 * @param string $text Text to convert
204 * @param string $variant Variant language code
205 * @return string Translated text
207 function translate( $text, $variant ) {
208 wfProfileIn( __METHOD__
);
209 if( !$this->mTablesLoaded
)
211 $text = $this->mTables
[$variant]->replace( $text );
212 wfProfileOut( __METHOD__
);
217 * convert text to all supported variants
219 * @param string $text the text to be converted
220 * @return array of string
223 function autoConvertToAllVariants($text) {
224 $fname="LanguageConverter::autoConvertToAllVariants";
225 wfProfileIn( $fname );
226 if( !$this->mTablesLoaded
)
230 foreach($this->mVariants
as $variant) {
231 $ret[$variant] = $this->translate($text, $variant);
234 wfProfileOut( $fname );
239 * convert link text to all supported variants
241 * @param string $text the text to be converted
242 * @return array of string
245 function convertLinkToAllVariants($text) {
246 if( !$this->mTablesLoaded
)
250 $tarray = explode($this->mMarkup
['begin'], $text);
251 $tfirst = array_shift($tarray);
253 foreach($this->mVariants
as $variant)
254 $ret[$variant] = $this->translate($tfirst,$variant);
256 foreach($tarray as $txt) {
257 $marked = explode($this->mMarkup
['end'], $txt, 2);
259 foreach($this->mVariants
as $variant){
260 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
261 if(array_key_exists(1, $marked))
262 $ret[$variant] .= $this->translate($marked[1],$variant);
272 * Convert text using a parser object for context
274 function parserConvert( $text, &$parser ) {
275 global $wgDisableLangConversion;
276 /* don't do anything if this is the conversion table */
277 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
278 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
283 if($wgDisableLangConversion)
286 $text = $this->convert( $text );
287 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
292 * Parse flags with syntax -{FLAG| ... }-
295 function parseFlags($marked){
298 // process flag only if the flag is valid
299 if(strlen($marked) < 2 ||
!(in_array($marked[0],$this->mFlags
) && $marked[1]=='|' ) )
300 return array($marked,array());
302 $tt = explode($this->mMarkup
['flagsep'], $marked, 2);
304 if(sizeof($tt) == 2) {
305 $f = explode($this->mMarkup
['varsep'], $tt[0]);
308 if(array_key_exists($ff, $this->mFlags
) &&
309 !array_key_exists($this->mFlags
[$ff], $flags))
310 $flags[] = $this->mFlags
[$ff];
317 if( !in_array('R',$flags) ){
318 //FIXME: may cause trouble here...
319 //strip since it interferes with the parsing, plus,
320 //all spaces should be stripped in this tag anyway.
321 $rules = str_replace(' ', '', $rules);
324 return array($rules,$flags);
328 * convert text to different variants of a language. the automatic
329 * conversion is done in autoConvert(). here we parse the text
330 * marked with -{}-, which specifies special conversions of the
331 * text that can not be accomplished in autoConvert()
333 * syntax of the markup:
334 * -{code1:text1;code2:text2;...}- or
335 * -{text}- in which case no conversion should take place for text
337 * @param string $text text to be converted
338 * @param bool $isTitle whether this conversion is for the article title
339 * @return string converted text
342 function convert( $text , $isTitle=false) {
343 $mw =& MagicWord
::get( 'notitleconvert' );
344 if( $mw->matchAndRemove( $text ) )
345 $this->mDoTitleConvert
= false;
347 $mw =& MagicWord
::get( 'nocontentconvert' );
348 if( $mw->matchAndRemove( $text ) ) {
349 $this->mDoContentConvert
= false;
352 // no conversion if redirecting
353 $mw =& MagicWord
::get( 'redirect' );
354 if( $mw->matchStart( $text ))
359 // use the title from the T flag if any
360 if($this->mTitleFromFlag
){
361 $this->mTitleFromFlag
= false;
362 return $this->mTitleDisplay
;
365 // check for __NOTC__ tag
366 if( !$this->mDoTitleConvert
) {
367 $this->mTitleDisplay
= $text;
372 $isredir = $wgRequest->getText( 'redirect', 'yes' );
373 $action = $wgRequest->getText( 'action' );
374 if ( $isredir == 'no' ||
$action == 'edit' ) {
378 $this->mTitleDisplay
= $this->convert($text);
379 return $this->mTitleDisplay
;
383 $plang = $this->getPreferredVariant();
384 if( isset( $this->mVariantFallbacks
[$plang] ) ) {
385 $fallback = $this->mVariantFallbacks
[$plang];
387 $fallback = $this->mMainLanguageCode
;
390 $tarray = explode($this->mMarkup
['begin'], $text);
391 $tfirst = array_shift($tarray);
392 if($this->mDoContentConvert
)
393 $text = $this->autoConvert($tfirst);
396 foreach($tarray as $txt) {
397 $marked = explode($this->mMarkup
['end'], $txt, 2);
399 // strip the flags from syntax like -{T| ... }-
400 list($rules,$flags) = $this->parseFlags($marked[0]);
402 // proces R flag: output raw content of -{ ... }-
403 if( in_array('R',$flags) ){
405 } else if( $this->mDoContentConvert
){
406 // parse the contents -{ ... }-
407 $carray = $this->parseManualRule($rules, $flags);
410 if(array_key_exists($plang, $carray)) {
411 $disp = $carray[$plang];
412 } else if(array_key_exists($fallback, $carray)) {
413 $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 $this->loadDefaultTables();
625 foreach($this->mVariants
as $var) {
626 $cached = $this->parseCachedTable($var);
627 $this->mTables
[$var]->mergeArray($cached);
630 $this->postLoadTables();
631 $this->mTables
['VERSION 2'] = true;
633 if($this->lockCache()) {
634 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
635 $this->unlockCache();
637 wfProfileOut( __METHOD__
.'-recache' );
639 wfProfileOut( __METHOD__
);
643 * Hook for post processig after conversion tables are loaded
646 function postLoadTables() {}
649 * Reload the conversion tables
653 function reloadTables() {
655 unset($this->mTables
);
656 $this->mTablesLoaded
= false;
657 $this->loadTables(false);
662 * parse the conversion table stored in the cache
664 * the tables should be in blocks of the following form:
672 * to make the tables more manageable, subpages are allowed
673 * and will be parsed recursively if $recursive=true
677 function parseCachedTable($code, $subpage='', $recursive=true) {
678 global $wgMessageCache;
679 static $parsed = array();
681 if(!is_object($wgMessageCache))
684 $key = 'Conversiontable/'.$code;
686 $key .= '/' . $subpage;
688 if(array_key_exists($key, $parsed))
692 $txt = $wgMessageCache->get( $key, true, true, true );
694 // get all subpage links of the form
695 // [[MediaWiki:conversiontable/zh-xx/...|...]]
696 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
697 $subs = explode('[[', $txt);
699 foreach( $subs as $sub ) {
700 $link = explode(']]', $sub, 2);
701 if(count($link) != 2)
703 $b = explode('|', $link[0]);
704 $b = explode('/', trim($b[0]), 3);
710 if($b[0] == $linkhead && $b[1] == $code) {
711 $sublinks[] = $sublink;
716 // parse the mappings in this page
717 $blocks = explode($this->mMarkup
['begin'], $txt);
718 array_shift($blocks);
720 foreach($blocks as $block) {
721 $mappings = explode($this->mMarkup
['end'], $block, 2);
722 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
723 $table = explode( ';', $stripped );
724 foreach( $table as $t ) {
725 $m = explode( '=>', $t );
726 if( count( $m ) != 2)
728 // trim any trailling comments starting with '//'
729 $tt = explode('//', $m[1], 2);
730 $ret[trim($m[0])] = trim($tt[0]);
733 $parsed[$key] = true;
736 // recursively parse the subpages
738 foreach($sublinks as $link) {
739 $s = $this->parseCachedTable($code, $link, $recursive);
740 $ret = array_merge($ret, $s);
744 if ($this->mUcfirst
) {
745 foreach ($ret as $k => $v) {
746 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
753 * Enclose a string with the "no conversion" tag. This is used by
754 * various functions in the Parser
756 * @param string $text text to be tagged for no conversion
757 * @return string the tagged text
759 function markNoConversion($text, $noParse=false) {
760 # don't mark if already marked
761 if(strpos($text, $this->mMarkup
['begin']) ||
762 strpos($text, $this->mMarkup
['end']))
765 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
770 * convert the sorting key for category links. this should make different
771 * keys that are variants of each other map to the same key
773 function convertCategoryKey( $key ) {
777 * hook to refresh the cache of conversion tables when
778 * MediaWiki:conversiontable* is updated
781 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
782 $titleobj = $article->getTitle();
783 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
785 global $wgContLang; // should be an LanguageZh.
786 if(get_class($wgContLang) != 'languagezh')
789 $title = $titleobj->getDBkey();
790 $t = explode('/', $title, 3);
792 if( $c > 1 && $t[0] == 'Conversiontable' ) {
793 if(in_array($t[1], $this->mVariants
)) {
794 $this->reloadTables();
802 * Armour rendered math against conversion
803 * Wrap math into rawoutput -{R| math }- syntax
805 function armourMath($text){
806 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];