Localisation updates for core messages from translatewiki.net (2009-03-09 22:54 UTC)
[mediawiki.git] / languages / LanguageConverter.php
blob3be46f90438447808062d026e60d727b9f8deaf1
1 <?php
3 /**
4 * Contains the LanguageConverter class and ConverterRule class
5 * @ingroup Language
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
8 * @file
9 */
11 /**
12 * base class for language convert
13 * @ingroup Language
15 * @author Zhengzhu Feng <zhengzhu@gmail.com>
16 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>, PhiLiP <philip.npc@gmail.com>
18 class LanguageConverter {
19 var $mPreferredVariant='';
20 var $mMainLanguageCode;
21 var $mVariants, $mVariantFallbacks, $mVariantNames;
22 var $mTablesLoaded = false;
23 var $mTables;
24 var $mManualAddTables;
25 var $mManualRemoveTables;
26 var $mNamespaceTables;
27 var $mTitleDisplay='';
28 var $mDoTitleConvert=true, $mDoContentConvert=true;
29 var $mManualLevel; // 'bidirectional' 'unidirectional' 'disable' for each variants
30 var $mTitleFromFlag = false;
31 var $mCacheKey;
32 var $mLangObj;
33 var $mMarkup;
34 var $mFlags;
35 var $mDescCodeSep = ':',$mDescVarSep = ';';
36 var $mUcfirst = false;
38 const CACHE_VERSION_KEY = 'VERSION 6';
40 /**
41 * Constructor
43 * @param string $maincode the main language code of this language
44 * @param array $variants the supported variants of this language
45 * @param array $variantfallback the fallback language of each variant
46 * @param array $markup array defining the markup used for manual conversion
47 * @param array $flags array defining the custom strings that maps to the flags
48 * @param array $manualLevel limit for supported variants
49 * @public
51 function __construct($langobj, $maincode,
52 $variants=array(),
53 $variantfallbacks=array(),
54 $markup=array(),
55 $flags = array(),
56 $manualLevel = array() ) {
57 $this->mLangObj = $langobj;
58 $this->mMainLanguageCode = $maincode;
59 $this->mVariants = $variants;
60 $this->mVariantFallbacks = $variantfallbacks;
61 global $wgLanguageNames;
62 $this->mVariantNames = $wgLanguageNames;
63 $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
64 $m = array(
65 'begin'=>'-{',
66 'flagsep'=>'|',
67 'unidsep'=>'=>', //for unidirectional conversion
68 'codesep'=>':',
69 'varsep'=>';',
70 'end'=>'}-'
72 $this->mMarkup = array_merge($m, $markup);
73 $f = array(
74 // 'S' show converted text
75 // '+' add rules for alltext
76 // 'E' the gave flags is error
77 // these flags above are reserved for program
78 'A'=>'A', // add rule for convert code (all text convert)
79 'T'=>'T', // title convert
80 'R'=>'R', // raw content
81 'D'=>'D', // convert description (subclass implement)
82 '-'=>'-', // remove convert (not implement)
83 'H'=>'H', // add rule for convert code (but no display in placed code )
84 'N'=>'N' // current variant name
86 $this->mFlags = array_merge($f, $flags);
87 foreach( $this->mVariants as $v) {
88 $this->mManualLevel[$v]=array_key_exists($v,$manualLevel)
89 ?$manualLevel[$v]
90 :'bidirectional';
91 $this->mManualAddTables[$v] = array();
92 $this->mManualRemoveTables[$v] = array();
93 $this->mNamespaceTables[$v] = array();
94 $this->mFlags[$v] = $v;
98 /**
99 * @public
101 function getVariants() {
102 return $this->mVariants;
106 * in case some variant is not defined in the markup, we need
107 * to have some fallback. for example, in zh, normally people
108 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
109 * when zh-sg is preferred but not defined, we will pick zh-hans
110 * in this case. right now this is only used by zh.
112 * @param string $v the language code of the variant
113 * @return string array the code of the fallback language or false if there is no fallback
114 * @public
116 function getVariantFallbacks($v) {
117 if( isset( $this->mVariantFallbacks[$v] ) ) {
118 return $this->mVariantFallbacks[$v];
120 return $this->mMainLanguageCode;
124 * get preferred language variants.
125 * @param boolean $fromUser Get it from $wgUser's preferences
126 * @return string the preferred language code
127 * @public
129 function getPreferredVariant( $fromUser = true ) {
130 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
132 if($this->mPreferredVariant)
133 return $this->mPreferredVariant;
135 // figure out user lang without constructing wgLang to avoid infinite recursion
136 if( $fromUser )
137 $defaultUserLang = $wgUser->getOption( 'language' );
138 else
139 $defaultUserLang = $this->mMainLanguageCode;
140 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
141 // see if interface language is same as content, if not, prevent conversion
142 if( ! in_array( $userLang, $this->mVariants ) ){
143 $this->mPreferredVariant = $this->mMainLanguageCode; // no conversion
144 return $this->mPreferredVariant;
147 // see if the preference is set in the request
148 $req = $wgRequest->getText( 'variant' );
149 if( in_array( $req, $this->mVariants ) ) {
150 $this->mPreferredVariant = $req;
151 return $req;
154 // check the syntax /code/ArticleTitle
155 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
156 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
157 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
158 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
159 if(in_array($scriptBase,$this->mVariants)){
160 $this->mPreferredVariant = $scriptBase;
161 return $this->mPreferredVariant;
165 // get language variant preference from logged in users
166 // Don't call this on stub objects because that causes infinite
167 // recursion during initialisation
168 if( $fromUser && $wgUser->isLoggedIn() ) {
169 $this->mPreferredVariant = $wgUser->getOption('variant');
170 return $this->mPreferredVariant;
173 // see if default variant is globaly set
174 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants )){
175 $this->mPreferredVariant = $wgDefaultLanguageVariant;
176 return $this->mPreferredVariant;
179 # FIXME rewrite code for parsing http header. The current code
180 # is written specific for detecting zh- variants
181 if( !$this->mPreferredVariant ) {
182 // see if some supported language variant is set in the
183 // http header, but we don't set the mPreferredVariant
184 // variable in case this is called before the user's
185 // preference is loaded
186 $pv=$this->mMainLanguageCode;
187 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
188 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
189 $zh = strstr($header, $pv.'-');
190 if($zh) {
191 $ary = split("[,;]",$zh);
192 $pv = $ary[0];
195 // don't try to return bad variant
196 if(in_array( $pv, $this->mVariants ))
197 return $pv;
200 return $this->mMainLanguageCode;
205 * caption convert, base on preg_replace_callback
207 * to convert text in "title" or "alt", like '<img alt="text" ... '
208 * or '<span title="text" ... '
210 * @return string like ' alt="yyyy"' or ' title="yyyy"'
211 * @private
213 function captionConvert( $matches ) {
214 $toVariant = $this->getPreferredVariant();
215 $title = $matches[1];
216 $text = $matches[2];
217 // we convert captions except URL
218 if( !strpos( $text, '://' ) )
219 $text = $this->translate($text, $toVariant);
220 return " $title=\"$text\"";
224 * dictionary-based conversion
226 * @param string $text the text to be converted
227 * @param string $toVariant the target language code
228 * @return string the converted text
229 * @private
231 function autoConvert($text, $toVariant=false) {
232 $fname="LanguageConverter::autoConvert";
234 wfProfileIn( $fname );
236 if(!$this->mTablesLoaded)
237 $this->loadTables();
239 if(!$toVariant)
240 $toVariant = $this->getPreferredVariant();
241 if(!in_array($toVariant, $this->mVariants))
242 return $text;
244 /* we convert everything except:
245 1. html markups (anything between < and >)
246 2. html entities
247 3. place holders created by the parser
249 global $wgParser;
250 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
251 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
252 } else
253 $marker = "";
255 // this one is needed when the text is inside an html markup
256 $htmlfix = '|<[^>]+$|^[^<>]*>';
258 // disable convert to variants between <code></code> tags
259 $codefix = '<code>.+?<\/code>|';
260 // disable convertsion of <script type="text/javascript"> ... </script>
261 $scriptfix = '<script.*?>.*?<\/script>|';
262 // disable conversion of <pre xxxx> ... </pre>
263 $prefix = '<pre.*?>.*?<\/pre>|';
265 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
267 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
269 $m = array_shift($matches);
271 $ret = $this->translate($m[0], $toVariant);
272 $mstart = $m[1]+strlen($m[0]);
274 // enable convertsion of '<img alt="xxxx" ... ' or '<span title="xxxx" ... '
275 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
276 foreach($matches as $m) {
277 $mark = substr($text, $mstart, $m[1]-$mstart);
278 $mark = preg_replace_callback($captionpattern, array(&$this, 'captionConvert'), $mark);
279 $ret .= $mark;
280 $ret .= $this->translate($m[0], $toVariant);
281 $mstart = $m[1] + strlen($m[0]);
283 wfProfileOut( $fname );
284 return $ret;
288 * Translate a string to a variant
289 * Doesn't process markup or do any of that other stuff, for that use convert()
291 * @param string $text Text to convert
292 * @param string $variant Variant language code
293 * @return string Translated text
294 * @private
296 function translate( $text, $variant ) {
297 wfProfileIn( __METHOD__ );
298 if( !$this->mTablesLoaded )
299 $this->loadTables();
300 $text = $this->mTables[$variant]->replace( $text );
301 wfProfileOut( __METHOD__ );
302 return $text;
306 * convert text to all supported variants
308 * @param string $text the text to be converted
309 * @return array of string
310 * @public
312 function autoConvertToAllVariants($text) {
313 $fname="LanguageConverter::autoConvertToAllVariants";
314 wfProfileIn( $fname );
315 if( !$this->mTablesLoaded )
316 $this->loadTables();
318 $ret = array();
319 foreach($this->mVariants as $variant) {
320 $ret[$variant] = $this->translate($text, $variant);
323 wfProfileOut( $fname );
324 return $ret;
328 * convert link text to all supported variants
330 * @param string $text the text to be converted
331 * @return array of string
332 * @public
334 function convertLinkToAllVariants($text) {
335 if( !$this->mTablesLoaded )
336 $this->loadTables();
338 $ret = array();
339 $tarray = explode($this->mMarkup['begin'], $text);
340 $tfirst = array_shift($tarray);
342 foreach($this->mVariants as $variant)
343 $ret[$variant] = $this->translate($tfirst,$variant);
345 foreach($tarray as $txt) {
346 $marked = explode($this->mMarkup['end'], $txt, 2);
348 foreach($this->mVariants as $variant){
349 $ret[$variant] .= $this->mMarkup['begin'].$marked[0].$this->mMarkup['end'];
350 if(array_key_exists(1, $marked))
351 $ret[$variant] .= $this->translate($marked[1],$variant);
356 return $ret;
360 * prepare manual conversion table
361 * @private
363 function prepareManualConv( $convRule ){
364 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
365 $title = $convRule->getTitle();
366 if( $title ){
367 $this->mTitleFromFlag = true;
368 $this->mTitleDisplay = $title;
371 //apply manual conversion table to global table
372 $convTable = $convRule->getConvTable();
373 $action = $convRule->getRulesAction();
374 foreach( $convTable as $v => $t ) {
375 if( !in_array( $v, $this->mVariants ) )continue;
376 if( $action=="add" ) {
377 foreach( $t as $from => $to ) {
378 // to ensure that $from and $to not be left blank
379 // so $this->translate() could always return a string
380 if ( $from || $to )
381 // more efficient than array_merge(), about 2.5 times.
382 $this->mManualAddTables[$v][$from] = $to;
385 elseif ( $action == "remove" ) {
386 foreach ( $t as $from=>$to ) {
387 if ( $from || $to )
388 $this->mManualRemoveTables[$v][$from] = $to;
395 * apply manual conversion from $this->mManualAddTables and $this->mManualRemoveTables
396 * @private
398 function applyManualConv(){
399 //apply manual conversion table to global table
400 foreach($this->mVariants as $v) {
401 if (count($this->mManualAddTables[$v]) > 0) {
402 $this->mTables[$v]->mergeArray($this->mManualAddTables[$v]);
404 if (count($this->mManualRemoveTables[$v]) > 0)
405 $this->mTables[$v]->removeArray($this->mManualRemoveTables[$v]);
410 * Convert text using a parser object for context
411 * @public
413 function parserConvert( $text, &$parser ) {
414 global $wgDisableLangConversion;
415 /* don't do anything if this is the conversion table */
416 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI &&
417 strpos($parser->mTitle->getText(), "Conversiontable") !== false )
419 return $text;
422 if ( $wgDisableLangConversion )
423 return $text;
425 $text = $this->convert( $text );
427 if ( $this->mTitleFromFlag )
428 $parser->mOutput->setTitleText( $this->mTitleDisplay );
429 return $text;
433 * convert namespace
434 * @param string $title the title included namespace
435 * @return array of string
436 * @private
438 function convertNamespace( $title, $variant ) {
439 $splittitle = explode( ':', $title );
440 if (count($splittitle) < 2)
441 return $title;
442 if ( isset( $this->mNamespaceTables[$variant][$splittitle[0]] ) )
443 $splittitle[0] = $this->mNamespaceTables[$variant][$splittitle[0]];
444 $ret = implode(':', $splittitle );
445 return $ret;
449 * convert title
450 * @private
452 function convertTitle( $text, $variant ){
453 global $wgDisableTitleConversion, $wgUser;
455 // check for global param and __NOTC__ tag
456 if( $wgDisableTitleConversion || !$this->mDoTitleConvert || $wgUser->getOption('noconvertlink') == 1 ) {
457 $this->mTitleDisplay = $text;
458 return $text;
461 // use the title from the T flag if any
462 if( $this->mTitleFromFlag ){
463 $this->mTitleFromFlag = false;
464 return $this->mTitleDisplay;
467 global $wgRequest;
468 $isredir = $wgRequest->getText( 'redirect', 'yes' );
469 $action = $wgRequest->getText( 'action' );
470 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
471 if ( $isredir == 'no' || $action == 'edit' || $action == 'submit' || $linkconvert == 'no' ) {
472 return $text;
473 } else {
474 $text = $this->convertNamespace( $text, $variant );
475 $this->mTitleDisplay = $this->convert( $text );
476 return $this->mTitleDisplay;
481 * convert text to different variants of a language. the automatic
482 * conversion is done in autoConvert(). here we parse the text
483 * marked with -{}-, which specifies special conversions of the
484 * text that can not be accomplished in autoConvert()
486 * syntax of the markup:
487 * -{code1:text1;code2:text2;...}- or
488 * -{flags|code1:text1;code2:text2;...}- or
489 * -{text}- in which case no conversion should take place for text
491 * @param string $text text to be converted
492 * @param bool $isTitle whether this conversion is for the article title
493 * @return string converted text
494 * @public
496 function convert( $text, $isTitle = false ) {
498 $mw =& MagicWord::get( 'notitleconvert' );
499 if( $mw->matchAndRemove( $text ) )
500 $this->mDoTitleConvert = false;
501 $mw =& MagicWord::get( 'nocontentconvert' );
502 if( $mw->matchAndRemove( $text ) ) {
503 $this->mDoContentConvert = false;
506 // no conversion if redirecting
507 $mw =& MagicWord::get( 'redirect' );
508 if( $mw->matchStart( $text ) )
509 return $text;
511 $plang = $this->getPreferredVariant();
513 // for title convertion
514 if ( $isTitle ) return $this->convertTitle( $text, $plang );
516 $tarray = StringUtils::explode( $this->mMarkup['end'], $text );
517 $text = '';
519 $marks = array();
520 foreach ( $tarray as $txt ) {
521 $marked = explode( $this->mMarkup['begin'], $txt, 2 );
522 if ( array_key_exists( 1, $marked ) ) {
523 $crule = new ConverterRule($marked[1], $this);
524 $crule->parse( $plang );
525 $marked[1] = $crule->getDisplay();
526 $this->prepareManualConv( $crule );
528 else
529 $marked[0] .= $this->mMarkup['end'];
530 array_push( $marks, $marked );
532 $this->applyManualConv();
533 foreach ( $marks as $marked ) {
534 if( $this->mDoContentConvert )
535 $text .= $this->autoConvert( $marked[0], $plang );
536 else
537 $text .= $marked[0];
538 if( array_key_exists( 1, $marked ) )
539 $text .= $marked[1];
541 // Remove the last delimiter (wasn't real)
542 $text = substr( $text, 0, -strlen( $this->mMarkup['end'] ) );
544 return $text;
548 * if a language supports multiple variants, it is
549 * possible that non-existing link in one variant
550 * actually exists in another variant. this function
551 * tries to find it. See e.g. LanguageZh.php
553 * @param string $link the name of the link
554 * @param mixed $nt the title object of the link
555 * @param boolean $ignoreOtherCond: to disable other conditions when
556 * we need to transclude a template or update a category's link
557 * @return null the input parameters may be modified upon return
558 * @public
560 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
561 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
562 $isredir = $wgRequest->getText( 'redirect', 'yes' );
563 $action = $wgRequest->getText( 'action' );
564 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
565 $disableLinkConversion = $wgDisableLangConversion || $wgDisableTitleConversion;
566 $linkBatch = new LinkBatch();
568 $ns=NS_MAIN;
570 if ( $disableLinkConversion || ( !$ignoreOtherCond && ( $isredir == 'no' || $action == 'edit'
571 || $action == 'submit' || $linkconvert == 'no' || $wgUser->getOption('noconvertlink') == 1 ) ) )
572 return;
574 if(is_object($nt))
575 $ns = $nt->getNamespace();
577 $variants = $this->autoConvertToAllVariants($link);
578 if($variants == false) //give up
579 return;
581 $titles = array();
583 foreach( $variants as $v ) {
584 if($v != $link){
585 $varnt = Title::newFromText( $v, $ns );
586 if(!is_null($varnt)){
587 $linkBatch->addObj($varnt);
588 $titles[]=$varnt;
593 // fetch all variants in single query
594 $linkBatch->execute();
596 foreach( $titles as $varnt ) {
597 if( $varnt->getArticleID() > 0 ) {
598 $nt = $varnt;
599 $link = $varnt->getText();
600 break;
606 * returns language specific hash options
608 * @public
610 function getExtraHashOptions() {
611 $variant = $this->getPreferredVariant();
612 return '!' . $variant ;
616 * get title text as defined in the body of the article text
618 * @public
620 function getParsedTitle() {
621 return $this->mTitleDisplay;
625 * a write lock to the cache
627 * @private
629 function lockCache() {
630 global $wgMemc;
631 $success = false;
632 for($i=0; $i<30; $i++) {
633 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
634 break;
635 sleep(1);
637 return $success;
641 * unlock cache
643 * @private
645 function unlockCache() {
646 global $wgMemc;
647 $wgMemc->delete($this->mCacheKey . "lock");
652 * Load default conversion tables
653 * This method must be implemented in derived class
655 * @private
657 function loadDefaultTables() {
658 $name = get_class($this);
659 wfDie("Must implement loadDefaultTables() method in class $name");
663 * load conversion tables either from the cache or the disk
664 * @private
666 function loadTables($fromcache=true) {
667 global $wgMemc;
668 if( $this->mTablesLoaded )
669 return;
670 wfProfileIn( __METHOD__ );
671 $this->mTablesLoaded = true;
672 $this->mTables = false;
673 if($fromcache) {
674 wfProfileIn( __METHOD__.'-cache' );
675 $this->mTables = $wgMemc->get( $this->mCacheKey );
676 wfProfileOut( __METHOD__.'-cache' );
678 if ( !$this->mTables || !isset( $this->mTables[self::CACHE_VERSION_KEY] ) ) {
679 wfProfileIn( __METHOD__.'-recache' );
680 // not in cache, or we need a fresh reload.
681 // we will first load the default tables
682 // then update them using things in MediaWiki:Zhconversiontable/*
683 $this->loadDefaultTables();
684 foreach($this->mVariants as $var) {
685 $cached = $this->parseCachedTable($var);
686 $this->mTables[$var]->mergeArray($cached);
689 $this->postLoadTables();
690 $this->mTables[self::CACHE_VERSION_KEY] = true;
692 if($this->lockCache()) {
693 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
694 $this->unlockCache();
696 wfProfileOut( __METHOD__.'-recache' );
698 wfProfileOut( __METHOD__ );
702 * Hook for post processig after conversion tables are loaded
705 function postLoadTables() {}
708 * Reload the conversion tables
710 * @private
712 function reloadTables() {
713 if($this->mTables)
714 unset($this->mTables);
715 $this->mTablesLoaded = false;
716 $this->loadTables(false);
721 * parse the conversion table stored in the cache
723 * the tables should be in blocks of the following form:
724 * -{
725 * word => word ;
726 * word => word ;
727 * ...
728 * }-
730 * to make the tables more manageable, subpages are allowed
731 * and will be parsed recursively if $recursive=true
734 function parseCachedTable($code, $subpage='', $recursive=true) {
735 global $wgMessageCache;
736 static $parsed = array();
738 if(!is_object($wgMessageCache))
739 return array();
741 $key = 'Conversiontable/'.$code;
742 if($subpage)
743 $key .= '/' . $subpage;
745 if(array_key_exists($key, $parsed))
746 return array();
748 if ( strpos( $code, '/' ) === false ) {
749 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
750 } else {
751 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Conversiontable/$code" );
752 if ( $title && $title->exists() ) {
753 $article = new Article( $title );
754 $txt = $article->getContents();
755 } else {
756 $txt = '';
760 // get all subpage links of the form
761 // [[MediaWiki:conversiontable/zh-xx/...|...]]
762 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
763 $subs = explode('[[', $txt);
764 $sublinks = array();
765 foreach( $subs as $sub ) {
766 $link = explode(']]', $sub, 2);
767 if(count($link) != 2)
768 continue;
769 $b = explode('|', $link[0]);
770 $b = explode('/', trim($b[0]), 3);
771 if(count($b)==3)
772 $sublink = $b[2];
773 else
774 $sublink = '';
776 if($b[0] == $linkhead && $b[1] == $code) {
777 $sublinks[] = $sublink;
782 // parse the mappings in this page
783 $blocks = explode($this->mMarkup['begin'], $txt);
784 array_shift($blocks);
785 $ret = array();
786 foreach($blocks as $block) {
787 $mappings = explode($this->mMarkup['end'], $block, 2);
788 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
789 $table = explode( ';', $stripped );
790 foreach( $table as $t ) {
791 $m = explode( '=>', $t );
792 if( count( $m ) != 2)
793 continue;
794 // trim any trailling comments starting with '//'
795 $tt = explode('//', $m[1], 2);
796 $ret[trim($m[0])] = trim($tt[0]);
799 $parsed[$key] = true;
802 // recursively parse the subpages
803 if($recursive) {
804 foreach($sublinks as $link) {
805 $s = $this->parseCachedTable($code, $link, $recursive);
806 $ret = array_merge($ret, $s);
810 if ($this->mUcfirst) {
811 foreach ($ret as $k => $v) {
812 $ret[Language::ucfirst($k)] = Language::ucfirst($v);
815 return $ret;
819 * Enclose a string with the "no conversion" tag. This is used by
820 * various functions in the Parser
822 * @param string $text text to be tagged for no conversion
823 * @return string the tagged text
824 * @public
826 function markNoConversion($text, $noParse=false) {
827 # don't mark if already marked
828 if(strpos($text, $this->mMarkup['begin']) ||
829 strpos($text, $this->mMarkup['end']))
830 return $text;
832 $ret = $this->mMarkup['begin'] .'R|'. $text . $this->mMarkup['end'];
833 return $ret;
837 * convert the sorting key for category links. this should make different
838 * keys that are variants of each other map to the same key
840 function convertCategoryKey( $key ) {
841 return $key;
844 * hook to refresh the cache of conversion tables when
845 * MediaWiki:conversiontable* is updated
846 * @private
848 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
849 $titleobj = $article->getTitle();
850 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
851 $title = $titleobj->getDBkey();
852 $t = explode('/', $title, 3);
853 $c = count($t);
854 if( $c > 1 && $t[0] == 'Conversiontable' ) {
855 if(in_array($t[1], $this->mVariants)) {
856 $this->reloadTables();
860 return true;
863 /**
864 * Armour rendered math against conversion
865 * Wrap math into rawoutput -{R| math }- syntax
866 * @public
868 function armourMath($text){
869 $ret = $this->mMarkup['begin'] . 'R|' . $text . $this->mMarkup['end'];
870 return $ret;
875 * parser for rules of language conversion , parse rules in -{ }- tag
876 * @ingroup Language
877 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
879 class ConverterRule {
880 var $mText; // original text in -{text}-
881 var $mConverter; // LanguageConverter object
882 var $mManualCodeError='<strong class="error">code error!</strong>';
883 var $mRuleDisplay = '',$mRuleTitle=false;
884 var $mRules = '';// string : the text of the rules
885 var $mRulesAction = 'none';
886 var $mFlags = array();
887 var $mConvTable = array();
888 var $mBidtable = array();// array of the translation in each variant
889 var $mUnidtable = array();// array of the translation in each variant
892 * Constructor
894 * @param string $text the text between -{ and }-
895 * @param object $converter a LanguageConverter object
896 * @access public
898 function __construct($text,$converter){
899 $this->mText = $text;
900 $this->mConverter=$converter;
901 foreach($converter->mVariants as $v){
902 $this->mConvTable[$v]=array();
907 * check if variants array in convert array
909 * @param string $variant Variant language code
910 * @return string Translated text
911 * @public
913 function getTextInBidtable($variants){
914 if(is_string($variants)){ $variants=array($variants); }
915 if(!is_array($variants)) return false;
916 foreach ($variants as $variant){
917 if(array_key_exists($variant, $this->mBidtable)){
918 return $this->mBidtable[$variant];
921 return false;
925 * Parse flags with syntax -{FLAG| ... }-
926 * @private
928 function parseFlags(){
929 $text = $this->mText;
930 if(strlen($text) < 2 ) {
931 $this->mFlags = array( 'R' );
932 $this->mRules = $text;
933 return;
936 $flags = array();
937 $markup = $this->mConverter->mMarkup;
938 $validFlags = $this->mConverter->mFlags;
939 $variants = $this->mConverter->mVariants;
941 $tt = explode($markup['flagsep'], $text, 2);
942 if(count($tt) == 2) {
943 $f = explode($markup['varsep'], $tt[0]);
944 foreach($f as $ff) {
945 $ff = trim($ff);
946 if(array_key_exists($ff, $validFlags) &&
947 !in_array($validFlags[$ff], $flags))
948 $flags[] = $validFlags[$ff];
950 $rules = $tt[1];
951 } else {
952 $rules = $text;
955 //check flags
956 if( in_array('R',$flags) ){
957 $flags = array('R');// remove other flags
958 } elseif ( in_array('N',$flags) ){
959 $flags = array('N');// remove other flags
960 } elseif ( in_array('-',$flags) ){
961 $flags = array('-');// remove other flags
962 } elseif (count($flags)==1 && $flags[0]=='T'){
963 $flags[]='H';
964 } elseif ( in_array('H',$flags) ){
965 // replace A flag, and remove other flags except T
966 $temp=array('+','H');
967 if(in_array('T',$flags)) $temp[] = 'T';
968 if(in_array('D',$flags)) $temp[] = 'D';
969 $flags = $temp;
970 } else {
971 if ( in_array('A',$flags) ) {
972 $flags[]='+';
973 $flags[]='S';
975 if ( in_array('D',$flags) )
976 $flags=array_diff($flags,array('S'));
977 $flags_temp = array();
978 foreach ($variants as $variant) {
979 // try to find flags like "zh-hans", "zh-hant"
980 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
981 if ( in_array($variant, $flags) )
982 $flags_temp[] = $variant;
984 if ( count($flags_temp) == 0 )
985 $flags = $flags_temp;
987 if ( count($flags) == 0 )
988 $flags = array('S');
989 $this->mRules=$rules;
990 $this->mFlags=$flags;
994 * generate conversion table
995 * @private
997 function parseRules() {
998 $rules = $this->mRules;
999 $flags = $this->mFlags;
1000 $bidtable = array();
1001 $unidtable = array();
1002 $markup = $this->mConverter->mMarkup;
1003 $variants = $this->mConverter->mVariants;
1005 // varsep_pattern for preg_split:
1006 // text should be splited by ";" only if a valid variant
1007 // name exist after the markup, for example:
1008 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:<span style="font-size:120%;">yyy</span>;}-
1009 // we should split it as:
1010 // array(
1011 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1012 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1013 // [2] => ''
1014 // )
1015 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1016 foreach( $variants as $variant ) {
1017 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|'; // zh-hans:xxx;zh-hant:yyy
1018 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1019 . '\s*' . $markup['codesep'] . '|'; // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1021 $varsep_pattern .= '\s*$)/';
1023 $choice = preg_split($varsep_pattern, $rules);
1025 foreach( $choice as $c ) {
1026 $v = explode($markup['codesep'], $c, 2);
1027 if( count($v) != 2 )
1028 continue;// syntax error, skip
1029 $to = trim($v[1]);
1030 $v = trim($v[0]);
1031 $u = explode($markup['unidsep'], $v);
1032 // if $to is empty, strtr() could return a wrong result
1033 if( count($u) == 1 && $to && in_array( $v, $variants ) ) {
1034 $bidtable[$v] = $to;
1035 } else if(count($u) == 2){
1036 $from = trim($u[0]);
1037 $v = trim($u[1]);
1038 if( array_key_exists( $v, $unidtable ) && !is_array( $unidtable[$v] )
1039 && $to && in_array( $v, $variants ) )
1040 $unidtable[$v] = array( $from=>$to );
1041 elseif ( $to && in_array( $v, $variants ) )
1042 $unidtable[$v][$from] = $to;
1044 // syntax error, pass
1045 if ( !array_key_exists( $v, $this->mConverter->mVariantNames ) ){
1046 $bidtable = array();
1047 $unidtable = array();
1048 break;
1051 $this->mBidtable = $bidtable;
1052 $this->mUnidtable = $unidtable;
1056 * @private
1058 function getRulesDesc(){
1059 $codesep = $this->mConverter->mDescCodeSep;
1060 $varsep = $this->mConverter->mDescVarSep;
1061 $text='';
1062 foreach($this->mBidtable as $k => $v)
1063 $text .= $this->mConverter->mVariantNames[$k]."$codesep$v$varsep";
1064 foreach($this->mUnidtable as $k => $a)
1065 foreach($a as $from=>$to)
1066 $text.=$from.'⇒'.$this->mConverter->mVariantNames[$k]."$codesep$to$varsep";
1067 return $text;
1071 * Parse rules conversion
1072 * @private
1074 function getRuleConvertedStr($variant,$doConvert){
1075 $bidtable = $this->mBidtable;
1076 $unidtable = $this->mUnidtable;
1078 if( count($bidtable) + count($unidtable) == 0 ){
1079 return $this->mRules;
1080 } elseif ($doConvert){// the text converted
1081 // display current variant in bidirectional array
1082 $disp = $this->getTextInBidtable($variant);
1083 // or display current variant in fallbacks
1084 if(!$disp)
1085 $disp = $this->getTextInBidtable(
1086 $this->mConverter->getVariantFallbacks($variant));
1087 // or display current variant in unidirectional array
1088 if(!$disp && array_key_exists($variant,$unidtable)){
1089 $disp = array_values($unidtable[$variant]);
1090 $disp = $disp[0];
1092 // or display frist text under disable manual convert
1093 if(!$disp && $this->mConverter->mManualLevel[$variant]=='disable') {
1094 if(count($bidtable)>0){
1095 $disp = array_values($bidtable);
1096 $disp = $disp[0];
1097 } else {
1098 $disp = array_values($unidtable);
1099 $disp = array_values($disp[0]);
1100 $disp = $disp[0];
1103 return $disp;
1104 } else {// no convert
1105 return $this->mRules;
1110 * generate conversion table for all text
1111 * @private
1113 function generateConvTable(){
1114 $flags = $this->mFlags;
1115 $bidtable = $this->mBidtable;
1116 $unidtable = $this->mUnidtable;
1117 $manLevel = $this->mConverter->mManualLevel;
1119 $vmarked=array();
1120 foreach($this->mConverter->mVariants as $v) {
1121 /* for bidirectional array
1122 fill in the missing variants, if any,
1123 with fallbacks */
1124 if(!array_key_exists($v, $bidtable)) {
1125 $variantFallbacks = $this->mConverter->getVariantFallbacks($v);
1126 $vf = $this->getTextInBidtable($variantFallbacks);
1127 if($vf) $bidtable[$v] = $vf;
1130 if(array_key_exists($v,$bidtable)){
1131 foreach($vmarked as $vo){
1132 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1133 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1134 // to introduce a custom mapping between
1135 // words WordZh and WordTw in the whole text
1136 if($manLevel[$v]=='bidirectional'){
1137 $this->mConvTable[$v][$bidtable[$vo]]=$bidtable[$v];
1139 if($manLevel[$vo]=='bidirectional'){
1140 $this->mConvTable[$vo][$bidtable[$v]]=$bidtable[$vo];
1143 $vmarked[]=$v;
1145 /*for unidirectional array
1146 fill to convert tables */
1147 $allow_unid = $manLevel[$v]=='bidirectional'
1148 || $manLevel[$v]=='unidirectional';
1149 if($allow_unid && array_key_exists($v,$unidtable)){
1150 $ct=$this->mConvTable[$v];
1151 $this->mConvTable[$v] = array_merge($ct,$unidtable[$v]);
1157 * Parse rules and flags
1158 * @public
1160 function parse($variant){
1161 if(!$variant)
1162 $variant = $this->mConverter->getPreferredVariant();
1164 $variants = $this->mConverter->mVariants;
1165 $this->parseFlags();
1166 $flags = $this->mFlags;
1168 // convert to specified variant
1169 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1170 if( count( array_diff( $flags, $variants ) ) == 0 and count( $flags ) != 0 ) {
1171 if ( in_array( $variant, $flags ) ) // check if current variant in flags
1172 // then convert <text to convert> to current language
1173 $this->mRules = $this->mConverter->autoConvert( $this->mRules, $variant );
1174 else { // if current variant no in flags,
1175 // then we check its fallback variants.
1176 $variantFallbacks = $this->mConverter->getVariantFallbacks($variant);
1177 foreach ( $variantFallbacks as $variantFallback ) {
1178 // if current variant's fallback exist in flags
1179 if ( in_array( $variantFallback, $flags ) ) {
1180 // then convert <text to convert> to fallback language
1181 $this->mRules = $this->mConverter->autoConvert( $this->mRules, $variantFallback );
1182 break;
1186 $this->mFlags = $flags = array('R');
1189 if( !in_array( 'R', $flags ) || !in_array( 'N', $flags ) ) {
1190 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1191 $this->mRules = str_replace('=&gt;','=>',$this->mRules);
1193 $this->parseRules();
1195 $rules = $this->mRules;
1197 if( count( $this->mBidtable ) == 0 && count( $this->mUnidtable ) == 0 ){
1198 if(in_array('+',$flags) || in_array('-',$flags))
1199 // fill all variants if text in -{A/H/-|text} without rules
1200 foreach($this->mConverter->mVariants as $v)
1201 $this->mBidtable[$v] = $rules;
1202 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1203 $this->mFlags = $flags = array('R');
1206 if( in_array('R',$flags) ) {
1207 // if we don't do content convert, still strip the -{}- tags
1208 $this->mRuleDisplay = $rules;
1209 } elseif ( in_array('N',$flags) ){
1210 // proces N flag: output current variant name
1211 $this->mRuleDisplay = $this->mConverter->mVariantNames[trim($rules)];
1212 } elseif ( in_array('D',$flags) ){
1213 // proces D flag: output rules description
1214 $this->mRuleDisplay = $this->getRulesDesc();
1215 } elseif ( in_array('H',$flags) || in_array('-',$flags) ) {
1216 // proces H,- flag or T only: output nothing
1217 $this->mRuleDisplay = '';
1218 } elseif ( in_array('S',$flags) ){
1219 $this->mRuleDisplay = $this->getRuleConvertedStr($variant,
1220 $this->mConverter->mDoContentConvert);
1221 } else {
1222 $this->mRuleDisplay= $this->mManualCodeError;
1224 // proces T flag
1225 if ( in_array('T',$flags) ) {
1226 $this->mRuleTitle = $this->getRuleConvertedStr($variant,
1227 $this->mConverter->mDoTitleConvert);
1230 if (in_array('-', $flags))
1231 $this->mRulesAction='remove';
1232 if (in_array('+', $flags))
1233 $this->mRulesAction='add';
1235 $this->generateConvTable();
1239 * @public
1241 function hasRules(){
1242 // TODO:
1246 * get display text on markup -{...}-
1247 * @public
1249 function getDisplay(){
1250 return $this->mRuleDisplay;
1253 * get converted title
1254 * @public
1256 function getTitle(){
1257 return $this->mRuleTitle;
1261 * return how deal with conversion rules
1262 * @public
1264 function getRulesAction(){
1265 return $this->mRulesAction;
1269 * get conversion table ( bidirectional and unidirectional conversion table )
1270 * @public
1272 function getConvTable(){
1273 return $this->mConvTable;
1277 * get conversion rules string
1278 * @public
1280 function getRules(){
1281 return $this->mRules;
1285 * get conversion flags
1286 * @public
1288 function getFlags(){
1289 return $this->mFlags;