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;
24 const CACHE_VERSION_KEY
= 'VERSION 5';
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
36 function __construct($langobj, $maincode,
38 $variantfallbacks=array(),
41 $this->mLangObj
= $langobj;
42 $this->mMainLanguageCode
= $maincode;
43 $this->mVariants
= $variants;
44 $this->mVariantFallbacks
= $variantfallbacks;
45 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
46 $m = array('begin'=>'-{', 'flagsep'=>'|', 'codesep'=>':',
47 'varsep'=>';', 'end'=>'}-');
48 $this->mMarkup
= array_merge($m, $markup);
49 $f = array('A'=>'A', 'T'=>'T', 'R' => 'R');
50 $this->mFlags
= array_merge($f, $flags);
56 function getVariants() {
57 return $this->mVariants
;
61 * in case some variant is not defined in the markup, we need
62 * to have some fallback. for example, in zh, normally people
63 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
64 * when zh-sg is preferred but not defined, we will pick zh-cn
65 * in this case. right now this is only used by zh.
67 * @param string $v the language code of the variant
68 * @return string the code of the fallback language or false if there is no fallback
71 function getVariantFallback($v) {
72 return $this->mVariantFallbacks
[$v];
77 * get preferred language variants.
78 * @param boolean $fromUser Get it from $wgUser's preferences
79 * @return string the preferred language code
82 function getPreferredVariant( $fromUser = true ) {
83 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
85 if($this->mPreferredVariant
)
86 return $this->mPreferredVariant
;
88 // see if the preference is set in the request
89 $req = $wgRequest->getText( 'variant' );
90 if( in_array( $req, $this->mVariants
) ) {
91 $this->mPreferredVariant
= $req;
95 // check the syntax /code/ArticleTitle
96 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
97 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
98 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
99 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
100 if(in_array($scriptBase,$this->mVariants
)){
101 $this->mPreferredVariant
= $scriptBase;
102 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 // see if default variant is globaly set
115 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants
)){
116 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
117 return $this->mPreferredVariant
;
120 # FIXME rewrite code for parsing http header. The current code
121 # is written specific for detecting zh- variants
122 if( !$this->mPreferredVariant
) {
123 // see if some supported language variant is set in the
124 // http header, but we don't set the mPreferredVariant
125 // variable in case this is called before the user's
126 // preference is loaded
127 $pv=$this->mMainLanguageCode
;
128 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
129 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
130 $zh = strstr($header, $pv.'-');
132 $pv = substr($zh,0,5);
135 // don't try to return bad variant
136 if(in_array( $pv, $this->mVariants
))
140 return $this->mMainLanguageCode
;
145 * dictionary-based conversion
147 * @param string $text the text to be converted
148 * @param string $toVariant the target language code
149 * @return string the converted text
152 function autoConvert($text, $toVariant=false) {
153 $fname="LanguageConverter::autoConvert";
155 wfProfileIn( $fname );
157 if(!$this->mTablesLoaded
)
161 $toVariant = $this->getPreferredVariant();
162 if(!in_array($toVariant, $this->mVariants
))
165 /* we convert everything except:
166 1. html markups (anything between < and >)
168 3. place holders created by the parser
171 if (isset($wgParser))
172 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
176 // this one is needed when the text is inside an html markup
177 $htmlfix = '|<[^>]+$|^[^<>]*>';
179 // disable convert to variants between <code></code> tags
180 $codefix = '<code>.+?<\/code>|';
181 // disable convertsion of <script type="text/javascript"> ... </script>
182 $scriptfix = '<script.*?>.*?<\/script>|';
184 $reg = '/'.$codefix . $scriptfix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
186 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
188 $m = array_shift($matches);
190 $ret = $this->translate($m[0], $toVariant);
191 $mstart = $m[1]+
strlen($m[0]);
192 foreach($matches as $m) {
193 $ret .= substr($text, $mstart, $m[1]-$mstart);
194 $ret .= $this->translate($m[0], $toVariant);
195 $mstart = $m[1] +
strlen($m[0]);
197 wfProfileOut( $fname );
202 * Translate a string to a variant
203 * Doesn't process markup or do any of that other stuff, for that use convert()
205 * @param string $text Text to convert
206 * @param string $variant Variant language code
207 * @return string Translated text
209 function translate( $text, $variant ) {
210 wfProfileIn( __METHOD__
);
211 if( !$this->mTablesLoaded
)
213 $text = $this->mTables
[$variant]->replace( $text );
214 wfProfileOut( __METHOD__
);
219 * convert text to all supported variants
221 * @param string $text the text to be converted
222 * @return array of string
225 function autoConvertToAllVariants($text) {
226 $fname="LanguageConverter::autoConvertToAllVariants";
227 wfProfileIn( $fname );
228 if( !$this->mTablesLoaded
)
232 foreach($this->mVariants
as $variant) {
233 $ret[$variant] = $this->translate($text, $variant);
236 wfProfileOut( $fname );
241 * convert link text to all supported variants
243 * @param string $text the text to be converted
244 * @return array of string
247 function convertLinkToAllVariants($text) {
248 if( !$this->mTablesLoaded
)
252 $tarray = explode($this->mMarkup
['begin'], $text);
253 $tfirst = array_shift($tarray);
255 foreach($this->mVariants
as $variant)
256 $ret[$variant] = $this->translate($tfirst,$variant);
258 foreach($tarray as $txt) {
259 $marked = explode($this->mMarkup
['end'], $txt, 2);
261 foreach($this->mVariants
as $variant){
262 $ret[$variant] .= $this->mMarkup
['begin'].$marked[0].$this->mMarkup
['end'];
263 if(array_key_exists(1, $marked))
264 $ret[$variant] .= $this->translate($marked[1],$variant);
274 * Convert text using a parser object for context
276 function parserConvert( $text, &$parser ) {
277 global $wgDisableLangConversion;
278 /* don't do anything if this is the conversion table */
279 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
&&
280 strpos($parser->mTitle
->getText(), "Conversiontable") !== false )
285 if($wgDisableLangConversion)
288 $text = $this->convert( $text );
289 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
294 * Parse flags with syntax -{FLAG| ... }-
297 function parseFlags($marked){
300 // process flag only if the flag is valid
301 if(strlen($marked) < 2 ||
!(in_array($marked[0],$this->mFlags
) && $marked[1]=='|' ) )
302 return array($marked,array());
304 $tt = explode($this->mMarkup
['flagsep'], $marked, 2);
306 if(sizeof($tt) == 2) {
307 $f = explode($this->mMarkup
['varsep'], $tt[0]);
310 if(array_key_exists($ff, $this->mFlags
) &&
311 !array_key_exists($this->mFlags
[$ff], $flags))
312 $flags[] = $this->mFlags
[$ff];
319 if( !in_array('R',$flags) ){
320 //FIXME: may cause trouble here...
321 //strip since it interferes with the parsing, plus,
322 //all spaces should be stripped in this tag anyway.
323 $rules = str_replace(' ', '', $rules);
326 return array($rules,$flags);
330 * convert text to different variants of a language. the automatic
331 * conversion is done in autoConvert(). here we parse the text
332 * marked with -{}-, which specifies special conversions of the
333 * text that can not be accomplished in autoConvert()
335 * syntax of the markup:
336 * -{code1:text1;code2:text2;...}- or
337 * -{text}- in which case no conversion should take place for text
339 * @param string $text text to be converted
340 * @param bool $isTitle whether this conversion is for the article title
341 * @return string converted text
344 function convert( $text , $isTitle=false) {
345 $mw =& MagicWord
::get( 'notitleconvert' );
346 if( $mw->matchAndRemove( $text ) )
347 $this->mDoTitleConvert
= false;
349 $mw =& MagicWord
::get( 'nocontentconvert' );
350 if( $mw->matchAndRemove( $text ) ) {
351 $this->mDoContentConvert
= false;
354 // no conversion if redirecting
355 $mw =& MagicWord
::get( 'redirect' );
356 if( $mw->matchStart( $text ))
361 // use the title from the T flag if any
362 if($this->mTitleFromFlag
){
363 $this->mTitleFromFlag
= false;
364 return $this->mTitleDisplay
;
367 // check for __NOTC__ tag
368 if( !$this->mDoTitleConvert
) {
369 $this->mTitleDisplay
= $text;
374 $isredir = $wgRequest->getText( 'redirect', 'yes' );
375 $action = $wgRequest->getText( 'action' );
376 if ( $isredir == 'no' ||
$action == 'edit' ) {
380 $this->mTitleDisplay
= $this->convert($text);
381 return $this->mTitleDisplay
;
385 $plang = $this->getPreferredVariant();
386 if( isset( $this->mVariantFallbacks
[$plang] ) ) {
387 $fallback = $this->mVariantFallbacks
[$plang];
389 $fallback = $this->mMainLanguageCode
;
392 $tarray = explode($this->mMarkup
['begin'], $text);
393 $tfirst = array_shift($tarray);
394 if($this->mDoContentConvert
)
395 $text = $this->autoConvert($tfirst);
398 foreach($tarray as $txt) {
399 $marked = explode($this->mMarkup
['end'], $txt, 2);
401 // strip the flags from syntax like -{T| ... }-
402 list($rules,$flags) = $this->parseFlags($marked[0]);
404 // proces R flag: output raw content of -{ ... }-
405 if( in_array('R',$flags) ){
407 } else if( $this->mDoContentConvert
){
408 // parse the contents -{ ... }-
409 $carray = $this->parseManualRule($rules, $flags);
412 if(array_key_exists($plang, $carray)) {
413 $disp = $carray[$plang];
414 } else if(array_key_exists($fallback, $carray)) {
415 $disp = $carray[$fallback];
418 // if we don't do content convert, still strip the -{}- tags
424 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
425 if(in_array('T', $flags)){
426 $this->mTitleFromFlag
= true;
427 $this->mTitleDisplay
= $disp;
432 // use syntax -{A|zh:WordZh;zh-tw:WordTw}- to introduce a custom mapping between
433 // words WordZh and WordTw in the whole text
434 if(in_array('A', $flags)) {
436 /* fill in the missing variants, if any,
438 foreach($this->mVariants
as $v) {
439 if(!array_key_exists($v, $carray)) {
440 $vf = $this->getVariantFallback($v);
441 if(array_key_exists($vf, $carray))
442 $carray[$v] = $carray[$vf];
446 foreach($this->mVariants
as $vfrom) {
447 if(!array_key_exists($vfrom, $carray))
449 foreach($this->mVariants
as $vto) {
452 if(!array_key_exists($vto, $carray))
454 $this->mTables
[$vto]->setPair($carray[$vfrom], $carray[$vto]);
462 if(array_key_exists(1, $marked)){
463 if( $this->mDoContentConvert
)
464 $text .= $this->autoConvert($marked[1]);
474 * parse the manually marked conversion rule
475 * @param string $rule the text of the rule
476 * @return array of the translation in each variant
479 function parseManualRule($rules, $flags=array()) {
481 $choice = explode($this->mMarkup
['varsep'], $rules);
483 if(sizeof($choice) == 1) {
484 /* a single choice */
485 foreach($this->mVariants
as $v)
486 $carray[$v] = $choice[0];
489 foreach($choice as $c) {
490 $v = explode($this->mMarkup
['codesep'], $c);
491 if(sizeof($v) != 2) // syntax error, skip
493 $carray[trim($v[0])] = trim($v[1]);
500 * if a language supports multiple variants, it is
501 * possible that non-existing link in one variant
502 * actually exists in another variant. this function
503 * tries to find it. See e.g. LanguageZh.php
505 * @param string $link the name of the link
506 * @param mixed $nt the title object of the link
507 * @return null the input parameters may be modified upon return
510 function findVariantLink( &$link, &$nt ) {
511 global $wgDisableLangConversion;
512 $linkBatch = new LinkBatch();
517 $ns = $nt->getNamespace();
519 $variants = $this->autoConvertToAllVariants($link);
520 if($variants == false) //give up
525 foreach( $variants as $v ) {
527 $varnt = Title
::newFromText( $v, $ns );
528 if(!is_null($varnt)){
529 $linkBatch->addObj($varnt);
535 // fetch all variants in single query
536 $linkBatch->execute();
538 foreach( $titles as $varnt ) {
539 if( $varnt->getArticleID() > 0 ) {
541 if( !$wgDisableLangConversion )
549 * returns language specific hash options
553 function getExtraHashOptions() {
554 $variant = $this->getPreferredVariant();
555 return '!' . $variant ;
559 * get title text as defined in the body of the article text
563 function getParsedTitle() {
564 return $this->mTitleDisplay
;
568 * a write lock to the cache
572 function lockCache() {
575 for($i=0; $i<30; $i++
) {
576 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
588 function unlockCache() {
590 $wgMemc->delete($this->mCacheKey
. "lock");
595 * Load default conversion tables
596 * This method must be implemented in derived class
600 function loadDefaultTables() {
601 $name = get_class($this);
602 wfDie("Must implement loadDefaultTables() method in class $name");
606 * load conversion tables either from the cache or the disk
609 function loadTables($fromcache=true) {
611 if( $this->mTablesLoaded
)
613 wfProfileIn( __METHOD__
);
614 $this->mTablesLoaded
= true;
615 $this->mTables
= false;
617 wfProfileIn( __METHOD__
.'-cache' );
618 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
619 wfProfileOut( __METHOD__
.'-cache' );
621 if ( !$this->mTables ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
622 wfProfileIn( __METHOD__
.'-recache' );
623 // not in cache, or we need a fresh reload.
624 // we will first load the default tables
625 // then update them using things in MediaWiki:Zhconversiontable/*
626 $this->loadDefaultTables();
627 foreach($this->mVariants
as $var) {
628 $cached = $this->parseCachedTable($var);
629 $this->mTables
[$var]->mergeArray($cached);
632 $this->postLoadTables();
633 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
635 if($this->lockCache()) {
636 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
637 $this->unlockCache();
639 wfProfileOut( __METHOD__
.'-recache' );
641 wfProfileOut( __METHOD__
);
645 * Hook for post processig after conversion tables are loaded
648 function postLoadTables() {}
651 * Reload the conversion tables
655 function reloadTables() {
657 unset($this->mTables
);
658 $this->mTablesLoaded
= false;
659 $this->loadTables(false);
664 * parse the conversion table stored in the cache
666 * the tables should be in blocks of the following form:
674 * to make the tables more manageable, subpages are allowed
675 * and will be parsed recursively if $recursive=true
679 function parseCachedTable($code, $subpage='', $recursive=true) {
680 global $wgMessageCache;
681 static $parsed = array();
683 if(!is_object($wgMessageCache))
686 $key = 'Conversiontable/'.$code;
688 $key .= '/' . $subpage;
690 if(array_key_exists($key, $parsed))
694 $txt = $wgMessageCache->get( $key, true, true, true );
696 // get all subpage links of the form
697 // [[MediaWiki:conversiontable/zh-xx/...|...]]
698 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
699 $subs = explode('[[', $txt);
701 foreach( $subs as $sub ) {
702 $link = explode(']]', $sub, 2);
703 if(count($link) != 2)
705 $b = explode('|', $link[0]);
706 $b = explode('/', trim($b[0]), 3);
712 if($b[0] == $linkhead && $b[1] == $code) {
713 $sublinks[] = $sublink;
718 // parse the mappings in this page
719 $blocks = explode($this->mMarkup
['begin'], $txt);
720 array_shift($blocks);
722 foreach($blocks as $block) {
723 $mappings = explode($this->mMarkup
['end'], $block, 2);
724 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
725 $table = explode( ';', $stripped );
726 foreach( $table as $t ) {
727 $m = explode( '=>', $t );
728 if( count( $m ) != 2)
730 // trim any trailling comments starting with '//'
731 $tt = explode('//', $m[1], 2);
732 $ret[trim($m[0])] = trim($tt[0]);
735 $parsed[$key] = true;
738 // recursively parse the subpages
740 foreach($sublinks as $link) {
741 $s = $this->parseCachedTable($code, $link, $recursive);
742 $ret = array_merge($ret, $s);
746 if ($this->mUcfirst
) {
747 foreach ($ret as $k => $v) {
748 $ret[Language
::ucfirst($k)] = Language
::ucfirst($v);
755 * Enclose a string with the "no conversion" tag. This is used by
756 * various functions in the Parser
758 * @param string $text text to be tagged for no conversion
759 * @return string the tagged text
761 function markNoConversion($text, $noParse=false) {
762 # don't mark if already marked
763 if(strpos($text, $this->mMarkup
['begin']) ||
764 strpos($text, $this->mMarkup
['end']))
767 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
772 * convert the sorting key for category links. this should make different
773 * keys that are variants of each other map to the same key
775 function convertCategoryKey( $key ) {
779 * hook to refresh the cache of conversion tables when
780 * MediaWiki:conversiontable* is updated
783 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
784 $titleobj = $article->getTitle();
785 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
787 global $wgContLang; // should be an LanguageZh.
788 if(get_class($wgContLang) != 'languagezh')
791 $title = $titleobj->getDBkey();
792 $t = explode('/', $title, 3);
794 if( $c > 1 && $t[0] == 'Conversiontable' ) {
795 if(in_array($t[1], $this->mVariants
)) {
796 $this->reloadTables();
804 * Armour rendered math against conversion
805 * Wrap math into rawoutput -{R| math }- syntax
807 function armourMath($text){
808 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];