Revert r37567 for nwo ("(bug 8604) padright: and similar functions fail with non...
[mediawiki.git] / languages / LanguageConverter.php
blobedaf4d68b15d923d6b73ac5bc9a2d2fcab82ac25
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>
18 class LanguageConverter {
19 var $mPreferredVariant='';
20 var $mMainLanguageCode;
21 var $mVariants, $mVariantFallbacks, $mVariantNames;
22 var $mTablesLoaded = false;
23 var $mTables;
24 var $mTitleDisplay='';
25 var $mDoTitleConvert=true, $mDoContentConvert=true;
26 var $mManualLevel; // 'bidirectional' 'unidirectional' 'disable' for each variants
27 var $mTitleFromFlag = false;
28 var $mCacheKey;
29 var $mLangObj;
30 var $mMarkup;
31 var $mFlags;
32 var $mDescCodeSep = ':',$mDescVarSep = ';';
33 var $mUcfirst = false;
35 const CACHE_VERSION_KEY = 'VERSION 6';
37 /**
38 * Constructor
40 * @param string $maincode the main language code of this language
41 * @param array $variants the supported variants of this language
42 * @param array $variantfallback the fallback language of each variant
43 * @param array $markup array defining the markup used for manual conversion
44 * @param array $flags array defining the custom strings that maps to the flags
45 * @param array $manualLevel limit for supported variants
46 * @public
48 function __construct($langobj, $maincode,
49 $variants=array(),
50 $variantfallbacks=array(),
51 $markup=array(),
52 $flags = array(),
53 $manualLevel = array() ) {
54 $this->mLangObj = $langobj;
55 $this->mMainLanguageCode = $maincode;
56 $this->mVariants = $variants;
57 $this->mVariantFallbacks = $variantfallbacks;
58 global $wgLanguageNames;
59 $this->mVariantNames = $wgLanguageNames;
60 $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
61 $m = array(
62 'begin'=>'-{',
63 'flagsep'=>'|',
64 'unidsep'=>'=>', //for unidirectional conversion
65 'codesep'=>':',
66 'varsep'=>';',
67 'end'=>'}-'
69 $this->mMarkup = array_merge($m, $markup);
70 $f = array(
71 // 'S' show converted text
72 // '+' add rules for alltext
73 // 'E' the gave flags is error
74 // these flags above are reserved for program
75 'A'=>'A', // add rule for convert code (all text convert)
76 'T'=>'T', // title convert
77 'R'=>'R', // raw content
78 'D'=>'D', // convert description (subclass implement)
79 '-'=>'-', // remove convert (not implement)
80 'H'=>'H', // add rule for convert code (but no display in placed code )
81 'N'=>'N' // current variant name
83 $this->mFlags = array_merge($f, $flags);
84 foreach( $this->mVariants as $v)
85 $this->mManualLevel[$v]=array_key_exists($v,$manualLevel)
86 ?$manualLevel[$v]
87 :'bidirectional';
90 /**
91 * @public
93 function getVariants() {
94 return $this->mVariants;
97 /**
98 * in case some variant is not defined in the markup, we need
99 * to have some fallback. for example, in zh, normally people
100 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
101 * when zh-sg is preferred but not defined, we will pick zh-hans
102 * in this case. right now this is only used by zh.
104 * @param string $v the language code of the variant
105 * @return string array the code of the fallback language or false if there is no fallback
106 * @public
108 function getVariantFallbacks($v) {
109 if( isset( $this->mVariantFallbacks[$v] ) ) {
110 return $this->mVariantFallbacks[$v];
112 return $this->mMainLanguageCode;
116 * get preferred language variants.
117 * @param boolean $fromUser Get it from $wgUser's preferences
118 * @return string the preferred language code
119 * @public
121 function getPreferredVariant( $fromUser = true ) {
122 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
124 if($this->mPreferredVariant)
125 return $this->mPreferredVariant;
127 // see if the preference is set in the request
128 $req = $wgRequest->getText( 'variant' );
129 if( in_array( $req, $this->mVariants ) ) {
130 $this->mPreferredVariant = $req;
131 return $req;
134 // check the syntax /code/ArticleTitle
135 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
136 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
137 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
138 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
139 if(in_array($scriptBase,$this->mVariants)){
140 $this->mPreferredVariant = $scriptBase;
141 return $this->mPreferredVariant;
145 // get language variant preference from logged in users
146 // Don't call this on stub objects because that causes infinite
147 // recursion during initialisation
148 if( $fromUser && $wgUser->isLoggedIn() ) {
149 $this->mPreferredVariant = $wgUser->getOption('variant');
150 return $this->mPreferredVariant;
153 // see if default variant is globaly set
154 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants )){
155 $this->mPreferredVariant = $wgDefaultLanguageVariant;
156 return $this->mPreferredVariant;
159 # FIXME rewrite code for parsing http header. The current code
160 # is written specific for detecting zh- variants
161 if( !$this->mPreferredVariant ) {
162 // see if some supported language variant is set in the
163 // http header, but we don't set the mPreferredVariant
164 // variable in case this is called before the user's
165 // preference is loaded
166 $pv=$this->mMainLanguageCode;
167 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
168 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
169 $zh = strstr($header, $pv.'-');
170 if($zh) {
171 $pv = substr($zh,0,5);
174 // don't try to return bad variant
175 if(in_array( $pv, $this->mVariants ))
176 return $pv;
179 return $this->mMainLanguageCode;
184 * dictionary-based conversion
186 * @param string $text the text to be converted
187 * @param string $toVariant the target language code
188 * @return string the converted text
189 * @private
191 function autoConvert($text, $toVariant=false) {
192 $fname="LanguageConverter::autoConvert";
194 wfProfileIn( $fname );
196 if(!$this->mTablesLoaded)
197 $this->loadTables();
199 if(!$toVariant)
200 $toVariant = $this->getPreferredVariant();
201 if(!in_array($toVariant, $this->mVariants))
202 return $text;
204 /* we convert everything except:
205 1. html markups (anything between < and >)
206 2. html entities
207 3. place holders created by the parser
209 global $wgParser;
210 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
211 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
212 } else
213 $marker = "";
215 // this one is needed when the text is inside an html markup
216 $htmlfix = '|<[^>]+$|^[^<>]*>';
218 // disable convert to variants between <code></code> tags
219 $codefix = '<code>.+?<\/code>|';
220 // disable convertsion of <script type="text/javascript"> ... </script>
221 $scriptfix = '<script.*?>.*?<\/script>|';
222 // disable conversion of <pre xxxx> ... </pre>
223 $prefix = '<pre.*?>.*?<\/pre>|';
225 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
227 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
229 $m = array_shift($matches);
231 $ret = $this->translate($m[0], $toVariant);
232 $mstart = $m[1]+strlen($m[0]);
233 foreach($matches as $m) {
234 $ret .= substr($text, $mstart, $m[1]-$mstart);
235 $ret .= $this->translate($m[0], $toVariant);
236 $mstart = $m[1] + strlen($m[0]);
238 wfProfileOut( $fname );
239 return $ret;
243 * Translate a string to a variant
244 * Doesn't process markup or do any of that other stuff, for that use convert()
246 * @param string $text Text to convert
247 * @param string $variant Variant language code
248 * @return string Translated text
249 * @private
251 function translate( $text, $variant ) {
252 wfProfileIn( __METHOD__ );
253 if( !$this->mTablesLoaded )
254 $this->loadTables();
255 $text = $this->mTables[$variant]->replace( $text );
256 wfProfileOut( __METHOD__ );
257 return $text;
261 * convert text to all supported variants
263 * @param string $text the text to be converted
264 * @return array of string
265 * @public
267 function autoConvertToAllVariants($text) {
268 $fname="LanguageConverter::autoConvertToAllVariants";
269 wfProfileIn( $fname );
270 if( !$this->mTablesLoaded )
271 $this->loadTables();
273 $ret = array();
274 foreach($this->mVariants as $variant) {
275 $ret[$variant] = $this->translate($text, $variant);
278 wfProfileOut( $fname );
279 return $ret;
283 * convert link text to all supported variants
285 * @param string $text the text to be converted
286 * @return array of string
287 * @public
289 function convertLinkToAllVariants($text) {
290 if( !$this->mTablesLoaded )
291 $this->loadTables();
293 $ret = array();
294 $tarray = explode($this->mMarkup['begin'], $text);
295 $tfirst = array_shift($tarray);
297 foreach($this->mVariants as $variant)
298 $ret[$variant] = $this->translate($tfirst,$variant);
300 foreach($tarray as $txt) {
301 $marked = explode($this->mMarkup['end'], $txt, 2);
303 foreach($this->mVariants as $variant){
304 $ret[$variant] .= $this->mMarkup['begin'].$marked[0].$this->mMarkup['end'];
305 if(array_key_exists(1, $marked))
306 $ret[$variant] .= $this->translate($marked[1],$variant);
311 return $ret;
316 * apply manual conversion
317 * @private
319 function applyManualConv($convRule){
320 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
321 $title = $convRule->getTitle();
322 if($title){
323 $this->mTitleFromFlag = true;
324 $this->mTitleDisplay = $title;
327 //apply manual conversion table to global table
328 $convTable = $convRule->getConvTable();
329 $action = $convRule->getRulesAction();
330 foreach($convTable as $v=>$t) {
331 if( !in_array($v,$this->mVariants) )continue;
332 if( $action=="add" )
333 $this->mTables[$v]->mergeArray($t);
334 elseif ( $action=="remove" )
335 $this->mTables[$v]->removeArray($t);
340 * Convert text using a parser object for context
341 * @public
343 function parserConvert( $text, &$parser ) {
344 global $wgDisableLangConversion;
345 /* don't do anything if this is the conversion table */
346 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI &&
347 strpos($parser->mTitle->getText(), "Conversiontable") !== false )
349 return $text;
352 if($wgDisableLangConversion)
353 return $text;
355 $text = $this->convert( $text );
356 $parser->mOutput->setTitleText( $this->mTitleDisplay );
357 return $text;
361 * convert title
362 * @private
364 function convertTitle($text){
365 // check for __NOTC__ tag
366 if( !$this->mDoTitleConvert ) {
367 $this->mTitleDisplay = $text;
368 return $text;
371 // use the title from the T flag if any
372 if($this->mTitleFromFlag){
373 $this->mTitleFromFlag = false;
374 return $this->mTitleDisplay;
377 global $wgRequest;
378 $isredir = $wgRequest->getText( 'redirect', 'yes' );
379 $action = $wgRequest->getText( 'action' );
380 if ( $isredir == 'no' || $action == 'edit' ) {
381 return $text;
382 } else {
383 $this->mTitleDisplay = $this->convert($text);
384 return $this->mTitleDisplay;
389 * convert text to different variants of a language. the automatic
390 * conversion is done in autoConvert(). here we parse the text
391 * marked with -{}-, which specifies special conversions of the
392 * text that can not be accomplished in autoConvert()
394 * syntax of the markup:
395 * -{code1:text1;code2:text2;...}- or
396 * -{flags|code1:text1;code2:text2;...}- or
397 * -{text}- in which case no conversion should take place for text
399 * @param string $text text to be converted
400 * @param bool $isTitle whether this conversion is for the article title
401 * @return string converted text
402 * @public
404 function convert( $text , $isTitle=false) {
406 $mw =& MagicWord::get( 'notitleconvert' );
407 if( $mw->matchAndRemove( $text ) )
408 $this->mDoTitleConvert = false;
409 $mw =& MagicWord::get( 'nocontentconvert' );
410 if( $mw->matchAndRemove( $text ) ) {
411 $this->mDoContentConvert = false;
414 // no conversion if redirecting
415 $mw =& MagicWord::get( 'redirect' );
416 if( $mw->matchStart( $text ))
417 return $text;
419 // for title convertion
420 if ($isTitle) return $this->convertTitle($text);
422 $plang = $this->getPreferredVariant();
423 $tarray = explode($this->mMarkup['end'], $text);
424 $text = '';
425 foreach($tarray as $txt) {
426 $marked = explode($this->mMarkup['begin'], $txt, 2);
428 if( $this->mDoContentConvert )
429 $text .= $this->autoConvert($marked[0],$plang);
430 else
431 $text .= $marked[0];
433 if(array_key_exists(1, $marked)){
434 // strip the flags from syntax like -{T| ... }-
435 $crule = new ConverterRule($marked[1], $this);
436 $crule->parse($plang);
438 $text .= $crule->getDisplay();
439 $this->applyManualConv($crule);
443 return $text;
447 * if a language supports multiple variants, it is
448 * possible that non-existing link in one variant
449 * actually exists in another variant. this function
450 * tries to find it. See e.g. LanguageZh.php
452 * @param string $link the name of the link
453 * @param mixed $nt the title object of the link
454 * @return null the input parameters may be modified upon return
455 * @public
457 function findVariantLink( &$link, &$nt ) {
458 global $wgDisableLangConversion;
459 $linkBatch = new LinkBatch();
461 $ns=NS_MAIN;
463 if(is_object($nt))
464 $ns = $nt->getNamespace();
466 $variants = $this->autoConvertToAllVariants($link);
467 if($variants == false) //give up
468 return;
470 $titles = array();
472 foreach( $variants as $v ) {
473 if($v != $link){
474 $varnt = Title::newFromText( $v, $ns );
475 if(!is_null($varnt)){
476 $linkBatch->addObj($varnt);
477 $titles[]=$varnt;
482 // fetch all variants in single query
483 $linkBatch->execute();
485 foreach( $titles as $varnt ) {
486 if( $varnt->getArticleID() > 0 ) {
487 $nt = $varnt;
488 if( !$wgDisableLangConversion )
489 $link = $v;
490 break;
496 * returns language specific hash options
498 * @public
500 function getExtraHashOptions() {
501 $variant = $this->getPreferredVariant();
502 return '!' . $variant ;
506 * get title text as defined in the body of the article text
508 * @public
510 function getParsedTitle() {
511 return $this->mTitleDisplay;
515 * a write lock to the cache
517 * @private
519 function lockCache() {
520 global $wgMemc;
521 $success = false;
522 for($i=0; $i<30; $i++) {
523 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
524 break;
525 sleep(1);
527 return $success;
531 * unlock cache
533 * @private
535 function unlockCache() {
536 global $wgMemc;
537 $wgMemc->delete($this->mCacheKey . "lock");
542 * Load default conversion tables
543 * This method must be implemented in derived class
545 * @private
547 function loadDefaultTables() {
548 $name = get_class($this);
549 wfDie("Must implement loadDefaultTables() method in class $name");
553 * load conversion tables either from the cache or the disk
554 * @private
556 function loadTables($fromcache=true) {
557 global $wgMemc;
558 if( $this->mTablesLoaded )
559 return;
560 wfProfileIn( __METHOD__ );
561 $this->mTablesLoaded = true;
562 $this->mTables = false;
563 if($fromcache) {
564 wfProfileIn( __METHOD__.'-cache' );
565 $this->mTables = $wgMemc->get( $this->mCacheKey );
566 wfProfileOut( __METHOD__.'-cache' );
568 if ( !$this->mTables || !isset( $this->mTables[self::CACHE_VERSION_KEY] ) ) {
569 wfProfileIn( __METHOD__.'-recache' );
570 // not in cache, or we need a fresh reload.
571 // we will first load the default tables
572 // then update them using things in MediaWiki:Zhconversiontable/*
573 $this->loadDefaultTables();
574 foreach($this->mVariants as $var) {
575 $cached = $this->parseCachedTable($var);
576 $this->mTables[$var]->mergeArray($cached);
579 $this->postLoadTables();
580 $this->mTables[self::CACHE_VERSION_KEY] = true;
582 if($this->lockCache()) {
583 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
584 $this->unlockCache();
586 wfProfileOut( __METHOD__.'-recache' );
588 wfProfileOut( __METHOD__ );
592 * Hook for post processig after conversion tables are loaded
595 function postLoadTables() {}
598 * Reload the conversion tables
600 * @private
602 function reloadTables() {
603 if($this->mTables)
604 unset($this->mTables);
605 $this->mTablesLoaded = false;
606 $this->loadTables(false);
611 * parse the conversion table stored in the cache
613 * the tables should be in blocks of the following form:
614 * -{
615 * word => word ;
616 * word => word ;
617 * ...
618 * }-
620 * to make the tables more manageable, subpages are allowed
621 * and will be parsed recursively if $recursive=true
624 function parseCachedTable($code, $subpage='', $recursive=true) {
625 global $wgMessageCache;
626 static $parsed = array();
628 if(!is_object($wgMessageCache))
629 return array();
631 $key = 'Conversiontable/'.$code;
632 if($subpage)
633 $key .= '/' . $subpage;
635 if(array_key_exists($key, $parsed))
636 return array();
638 if ( strpos( $code, '/' ) === false ) {
639 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
640 } else {
641 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Conversiontable/$code" );
642 if ( $title && $title->exists() ) {
643 $article = new Article( $title );
644 $txt = $article->getContents();
645 } else {
646 $txt = '';
650 // get all subpage links of the form
651 // [[MediaWiki:conversiontable/zh-xx/...|...]]
652 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
653 $subs = explode('[[', $txt);
654 $sublinks = array();
655 foreach( $subs as $sub ) {
656 $link = explode(']]', $sub, 2);
657 if(count($link) != 2)
658 continue;
659 $b = explode('|', $link[0]);
660 $b = explode('/', trim($b[0]), 3);
661 if(count($b)==3)
662 $sublink = $b[2];
663 else
664 $sublink = '';
666 if($b[0] == $linkhead && $b[1] == $code) {
667 $sublinks[] = $sublink;
672 // parse the mappings in this page
673 $blocks = explode($this->mMarkup['begin'], $txt);
674 array_shift($blocks);
675 $ret = array();
676 foreach($blocks as $block) {
677 $mappings = explode($this->mMarkup['end'], $block, 2);
678 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
679 $table = explode( ';', $stripped );
680 foreach( $table as $t ) {
681 $m = explode( '=>', $t );
682 if( count( $m ) != 2)
683 continue;
684 // trim any trailling comments starting with '//'
685 $tt = explode('//', $m[1], 2);
686 $ret[trim($m[0])] = trim($tt[0]);
689 $parsed[$key] = true;
692 // recursively parse the subpages
693 if($recursive) {
694 foreach($sublinks as $link) {
695 $s = $this->parseCachedTable($code, $link, $recursive);
696 $ret = array_merge($ret, $s);
700 if ($this->mUcfirst) {
701 foreach ($ret as $k => $v) {
702 $ret[Language::ucfirst($k)] = Language::ucfirst($v);
705 return $ret;
709 * Enclose a string with the "no conversion" tag. This is used by
710 * various functions in the Parser
712 * @param string $text text to be tagged for no conversion
713 * @return string the tagged text
714 * @public
716 function markNoConversion($text, $noParse=false) {
717 # don't mark if already marked
718 if(strpos($text, $this->mMarkup['begin']) ||
719 strpos($text, $this->mMarkup['end']))
720 return $text;
722 $ret = $this->mMarkup['begin'] .'R|'. $text . $this->mMarkup['end'];
723 return $ret;
727 * convert the sorting key for category links. this should make different
728 * keys that are variants of each other map to the same key
730 function convertCategoryKey( $key ) {
731 return $key;
734 * hook to refresh the cache of conversion tables when
735 * MediaWiki:conversiontable* is updated
736 * @private
738 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
739 $titleobj = $article->getTitle();
740 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
741 $title = $titleobj->getDBkey();
742 $t = explode('/', $title, 3);
743 $c = count($t);
744 if( $c > 1 && $t[0] == 'Conversiontable' ) {
745 if(in_array($t[1], $this->mVariants)) {
746 $this->reloadTables();
750 return true;
753 /**
754 * Armour rendered math against conversion
755 * Wrap math into rawoutput -{R| math }- syntax
756 * @public
758 function armourMath($text){
759 $ret = $this->mMarkup['begin'] . 'R|' . $text . $this->mMarkup['end'];
760 return $ret;
765 * parser for rules of language conversion , parse rules in -{ }- tag
766 * @ingroup Language
767 * @author fdcn <fdcn64@gmail.com>
769 class ConverterRule {
770 var $mText; // original text in -{text}-
771 var $mConverter; // LanguageConverter object
772 var $mManualCodeError='<strong class="error">code error!</strong>';
773 var $mRuleDisplay = '',$mRuleTitle=false;
774 var $mRules = '';// string : the text of the rules
775 var $mRulesAction = 'none';
776 var $mFlags = array();
777 var $mConvTable = array();
778 var $mBidtable = array();// array of the translation in each variant
779 var $mUnidtable = array();// array of the translation in each variant
782 * Constructor
784 * @param string $text the text between -{ and }-
785 * @param object $converter a LanguageConverter object
786 * @access public
788 function __construct($text,$converter){
789 $this->mText = $text;
790 $this->mConverter=$converter;
791 foreach($converter->mVariants as $v){
792 $this->mConvTable[$v]=array();
797 * check if variants array in convert array
799 * @param string $variant Variant language code
800 * @return string Translated text
801 * @public
803 function getTextInBidtable($variants){
804 if(is_string($variants)){ $variants=array($variants); }
805 if(!is_array($variants)) return false;
806 foreach ($variants as $variant){
807 if(array_key_exists($variant, $this->mBidtable)){
808 return $this->mBidtable[$variant];
811 return false;
815 * Parse flags with syntax -{FLAG| ... }-
816 * @private
818 function parseFlags(){
819 $text = $this->mText;
820 if(strlen($text) < 2 ) {
821 $this->mFlags = array( 'R' );
822 $this->mRules = $text;
823 return;
826 $flags = array();
827 $markup = $this->mConverter->mMarkup;
828 $validFlags = $this->mConverter->mFlags;
830 $tt = explode($markup['flagsep'], $text, 2);
831 if(count($tt) == 2) {
832 $f = explode($markup['varsep'], $tt[0]);
833 foreach($f as $ff) {
834 $ff = trim($ff);
835 if(array_key_exists($ff, $validFlags) &&
836 !in_array($validFlags[$ff], $flags))
837 $flags[] = $validFlags[$ff];
839 $rules = $tt[1];
840 } else {
841 $rules = $text;
844 //check flags
845 if( in_array('R',$flags) ){
846 $flags = array('R');// remove other flags
847 } elseif ( in_array('N',$flags) ){
848 $flags = array('N');// remove other flags
849 } elseif ( in_array('-',$flags) ){
850 $flags = array('-');// remove other flags
851 } elseif (count($flags)==1 && $flags[0]=='T'){
852 $flags[]='H';
853 } elseif ( in_array('H',$flags) ){
854 // replace A flag, and remove other flags except T
855 $temp=array('+','H');
856 if(in_array('T',$flags)) $temp[] = 'T';
857 if(in_array('D',$flags)) $temp[] = 'D';
858 $flags = $temp;
859 } else {
860 if ( in_array('A',$flags)) {
861 $flags[]='+';
862 $flags[]='S';
864 if ( in_array('D',$flags) )
865 $flags=array_diff($flags,array('S'));
867 if ( count($flags)==0 )
868 $flags = array('S');
869 $this->mRules=$rules;
870 $this->mFlags=$flags;
874 * generate conversion table
875 * @private
877 function parseRules() {
878 $rules = $this->mRules;
879 $flags = $this->mFlags;
880 $bidtable = array();
881 $unidtable = array();
882 $markup = $this->mConverter->mMarkup;
884 $choice = explode($markup['varsep'], $rules );
885 foreach($choice as $c) {
886 $v = explode($markup['codesep'], $c);
887 if(count($v) != 2)
888 continue;// syntax error, skip
889 $to=trim($v[1]);
890 $v=trim($v[0]);
891 $u = explode($markup['unidsep'], $v);
892 if(count($u) == 1) {
893 $bidtable[$v] = $to;
894 } else if(count($u) == 2){
895 $from=trim($u[0]);$v=trim($u[1]);
896 if( array_key_exists($v,$unidtable) && !is_array($unidtable[$v]) )
897 $unidtable[$v]=array($from=>$to);
898 else
899 $unidtable[$v][$from]=$to;
901 // syntax error, pass
902 if (!array_key_exists($v,$this->mConverter->mVariantNames)){
903 $bidtable = array();
904 $unidtable = array();
905 break;
908 $this->mBidtable = $bidtable;
909 $this->mUnidtable = $unidtable;
913 * @private
915 function getRulesDesc(){
916 $codesep = $this->mConverter->mDescCodeSep;
917 $varsep = $this->mConverter->mDescVarSep;
918 $text='';
919 foreach($this->mBidtable as $k => $v)
920 $text .= $this->mConverter->mVariantNames[$k]."$codesep$v$varsep";
921 foreach($this->mUnidtable as $k => $a)
922 foreach($a as $from=>$to)
923 $text.=$from.'⇒'.$this->mConverter->mVariantNames[$k]."$codesep$to$varsep";
924 return $text;
928 * Parse rules conversion
929 * @private
931 function getRuleConvertedStr($variant,$doConvert){
932 $bidtable = $this->mBidtable;
933 $unidtable = $this->mUnidtable;
935 if( count($bidtable) + count($unidtable) == 0 ){
936 return $this->mRules;
937 } elseif ($doConvert){// the text converted
938 // display current variant in bidirectional array
939 $disp = $this->getTextInBidtable($variant);
940 // or display current variant in fallbacks
941 if(!$disp)
942 $disp = $this->getTextInBidtable(
943 $this->mConverter->getVariantFallbacks($variant));
944 // or display current variant in unidirectional array
945 if(!$disp && array_key_exists($variant,$unidtable)){
946 $disp = array_values($unidtable[$variant]);
947 $disp = $disp[0];
949 // or display frist text under disable manual convert
950 if(!$disp && $this->mConverter->mManualLevel[$variant]=='disable') {
951 if(count($bidtable)>0){
952 $disp = array_values($bidtable);
953 $disp = $disp[0];
954 } else {
955 $disp = array_values($unidtable);
956 $disp = array_values($disp[0]);
957 $disp = $disp[0];
960 return $disp;
961 } else {// no convert
962 return $this->mRules;
967 * generate conversion table for all text
968 * @private
970 function generateConvTable(){
971 $flags = $this->mFlags;
972 $bidtable = $this->mBidtable;
973 $unidtable = $this->mUnidtable;
974 $manLevel = $this->mConverter->mManualLevel;
976 $vmarked=array();
977 foreach($this->mConverter->mVariants as $v) {
978 /* for bidirectional array
979 fill in the missing variants, if any,
980 with fallbacks */
981 if(!array_key_exists($v, $bidtable)) {
982 $variantFallbacks = $this->mConverter->getVariantFallbacks($v);
983 $vf = $this->getTextInBidtable($variantFallbacks);
984 if($vf) $bidtable[$v] = $vf;
987 if(array_key_exists($v,$bidtable)){
988 foreach($vmarked as $vo){
989 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
990 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
991 // to introduce a custom mapping between
992 // words WordZh and WordTw in the whole text
993 if($manLevel[$v]=='bidirectional'){
994 $this->mConvTable[$v][$bidtable[$vo]]=$bidtable[$v];
996 if($manLevel[$vo]=='bidirectional'){
997 $this->mConvTable[$vo][$bidtable[$v]]=$bidtable[$vo];
1000 $vmarked[]=$v;
1002 /*for unidirectional array
1003 fill to convert tables */
1004 $allow_unid = $manLevel[$v]=='bidirectional'
1005 || $manLevel[$v]=='unidirectional';
1006 if($allow_unid && array_key_exists($v,$unidtable)){
1007 $ct=$this->mConvTable[$v];
1008 $this->mConvTable[$v] = array_merge($ct,$unidtable[$v]);
1014 * Parse rules and flags
1015 * @public
1017 function parse($variant){
1018 if(!$variant) $variant = $this->mConverter->getPreferredVariant();
1020 $this->parseFlags();
1021 $flags = $this->mFlags;
1023 if( !in_array('R',$flags) || !in_array('N',$flags) ){
1024 //FIXME: may cause trouble here...
1025 //strip &nbsp; since it interferes with the parsing, plus,
1026 //all spaces should be stripped in this tag anyway.
1027 $this->mRules = str_replace('&nbsp;', '', $this->mRules);
1028 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1029 $this->mRules = str_replace('=&gt;','=>',$this->mRules);
1031 $this->parseRules();
1033 $rules = $this->mRules;
1035 if(count($this->mBidtable)==0 && count($this->mUnidtable)==0){
1036 if(in_array('+',$flags) || in_array('-',$flags))
1037 // fill all variants if text in -{A/H/-|text} without rules
1038 foreach($this->mConverter->mVariants as $v)
1039 $this->mBidtable[$v] = $rules;
1040 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1041 $this->mFlags = $flags = array('R');
1044 if( in_array('R',$flags) ) {
1045 // if we don't do content convert, still strip the -{}- tags
1046 $this->mRuleDisplay = $rules;
1047 } elseif ( in_array('N',$flags) ){
1048 // proces N flag: output current variant name
1049 $this->mRuleDisplay = $this->mConverter->mVariantNames[trim($rules)];
1050 } elseif ( in_array('D',$flags) ){
1051 // proces D flag: output rules description
1052 $this->mRuleDisplay = $this->getRulesDesc();
1053 } elseif ( in_array('H',$flags) || in_array('-',$flags) ) {
1054 // proces H,- flag or T only: output nothing
1055 $this->mRuleDisplay = '';
1056 } elseif ( in_array('S',$flags) ){
1057 $this->mRuleDisplay = $this->getRuleConvertedStr($variant,
1058 $this->mConverter->mDoContentConvert);
1059 } else {
1060 $this->mRuleDisplay= $this->mManualCodeError;
1062 // proces T flag
1063 if ( in_array('T',$flags) ) {
1064 $this->mRuleTitle = $this->getRuleConvertedStr($variant,
1065 $this->mConverter->mDoTitleConvert);
1068 if (in_array('-', $flags))
1069 $this->mRulesAction='remove';
1070 if (in_array('+', $flags))
1071 $this->mRulesAction='add';
1073 $this->generateConvTable();
1077 * @public
1079 function hasRules(){
1080 // TODO:
1084 * get display text on markup -{...}-
1085 * @public
1087 function getDisplay(){
1088 return $this->mRuleDisplay;
1091 * get converted title
1092 * @public
1094 function getTitle(){
1095 return $this->mRuleTitle;
1099 * return how deal with conversion rules
1100 * @public
1102 function getRulesAction(){
1103 return $this->mRulesAction;
1107 * get conversion table ( bidirectional and unidirectional conversion table )
1108 * @public
1110 function getConvTable(){
1111 return $this->mConvTable;
1115 * get conversion rules string
1116 * @public
1118 function getRules(){
1119 return $this->mRules;
1123 * get conversion flags
1124 * @public
1126 function getFlags(){
1127 return $this->mFlags;