* (bug 10837) Language variants overrides languages other than the variant main language.
[lhc/web/wiklou.git] / languages / LanguageConverter.php
1 <?php
2
3 /**
4 * Contains the LanguageConverter class and ConverterRule class
5 * @ingroup Language
6 *
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
8 * @file
9 */
10
11 /**
12 * base class for language convert
13 * @ingroup Language
14 *
15 * @author Zhengzhu Feng <zhengzhu@gmail.com>
16 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>
17 */
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;
34
35 const CACHE_VERSION_KEY = 'VERSION 6';
36
37 /**
38 * Constructor
39 *
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
47 */
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'=>'}-'
68 );
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
82 );
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';
88 }
89
90 /**
91 * @public
92 */
93 function getVariants() {
94 return $this->mVariants;
95 }
96
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.
103 *
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
107 */
108 function getVariantFallbacks($v) {
109 if( isset( $this->mVariantFallbacks[$v] ) ) {
110 return $this->mVariantFallbacks[$v];
111 }
112 return $this->mMainLanguageCode;
113 }
114
115 /**
116 * get preferred language variants.
117 * @param boolean $fromUser Get it from $wgUser's preferences
118 * @return string the preferred language code
119 * @public
120 */
121 function getPreferredVariant( $fromUser = true ) {
122 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
123
124 if($this->mPreferredVariant)
125 return $this->mPreferredVariant;
126
127 // figure out user lang without constructing wgLang to avoid infinite recursion
128 $userLang = $wgRequest->getVal( 'uselang', $wgUser->getOption( 'language' ) );
129 // see if interface language is same as content, if not, prevent conversion
130 if( $this->mMainLanguageCode != $userLang ){
131 $this->mPreferredVariant = $this->mMainLanguageCode; // no conversion
132 return $this->mPreferredVariant;
133 }
134
135 // see if the preference is set in the request
136 $req = $wgRequest->getText( 'variant' );
137 if( in_array( $req, $this->mVariants ) ) {
138 $this->mPreferredVariant = $req;
139 return $req;
140 }
141
142 // check the syntax /code/ArticleTitle
143 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
144 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
145 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
146 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
147 if(in_array($scriptBase,$this->mVariants)){
148 $this->mPreferredVariant = $scriptBase;
149 return $this->mPreferredVariant;
150 }
151 }
152
153 // get language variant preference from logged in users
154 // Don't call this on stub objects because that causes infinite
155 // recursion during initialisation
156 if( $fromUser && $wgUser->isLoggedIn() ) {
157 $this->mPreferredVariant = $wgUser->getOption('variant');
158 return $this->mPreferredVariant;
159 }
160
161 // see if default variant is globaly set
162 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants )){
163 $this->mPreferredVariant = $wgDefaultLanguageVariant;
164 return $this->mPreferredVariant;
165 }
166
167 # FIXME rewrite code for parsing http header. The current code
168 # is written specific for detecting zh- variants
169 if( !$this->mPreferredVariant ) {
170 // see if some supported language variant is set in the
171 // http header, but we don't set the mPreferredVariant
172 // variable in case this is called before the user's
173 // preference is loaded
174 $pv=$this->mMainLanguageCode;
175 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
176 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
177 $zh = strstr($header, $pv.'-');
178 if($zh) {
179 $pv = substr($zh,0,5);
180 }
181 }
182 // don't try to return bad variant
183 if(in_array( $pv, $this->mVariants ))
184 return $pv;
185 }
186
187 return $this->mMainLanguageCode;
188
189 }
190
191 /**
192 * dictionary-based conversion
193 *
194 * @param string $text the text to be converted
195 * @param string $toVariant the target language code
196 * @return string the converted text
197 * @private
198 */
199 function autoConvert($text, $toVariant=false) {
200 $fname="LanguageConverter::autoConvert";
201
202 wfProfileIn( $fname );
203
204 if(!$this->mTablesLoaded)
205 $this->loadTables();
206
207 if(!$toVariant)
208 $toVariant = $this->getPreferredVariant();
209 if(!in_array($toVariant, $this->mVariants))
210 return $text;
211
212 /* we convert everything except:
213 1. html markups (anything between < and >)
214 2. html entities
215 3. place holders created by the parser
216 */
217 global $wgParser;
218 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
219 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
220 } else
221 $marker = "";
222
223 // this one is needed when the text is inside an html markup
224 $htmlfix = '|<[^>]+$|^[^<>]*>';
225
226 // disable convert to variants between <code></code> tags
227 $codefix = '<code>.+?<\/code>|';
228 // disable convertsion of <script type="text/javascript"> ... </script>
229 $scriptfix = '<script.*?>.*?<\/script>|';
230 // disable conversion of <pre xxxx> ... </pre>
231 $prefix = '<pre.*?>.*?<\/pre>|';
232
233 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
234
235 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
236
237 $m = array_shift($matches);
238
239 $ret = $this->translate($m[0], $toVariant);
240 $mstart = $m[1]+strlen($m[0]);
241 foreach($matches as $m) {
242 $ret .= substr($text, $mstart, $m[1]-$mstart);
243 $ret .= $this->translate($m[0], $toVariant);
244 $mstart = $m[1] + strlen($m[0]);
245 }
246 wfProfileOut( $fname );
247 return $ret;
248 }
249
250 /**
251 * Translate a string to a variant
252 * Doesn't process markup or do any of that other stuff, for that use convert()
253 *
254 * @param string $text Text to convert
255 * @param string $variant Variant language code
256 * @return string Translated text
257 * @private
258 */
259 function translate( $text, $variant ) {
260 wfProfileIn( __METHOD__ );
261 if( !$this->mTablesLoaded )
262 $this->loadTables();
263 $text = $this->mTables[$variant]->replace( $text );
264 wfProfileOut( __METHOD__ );
265 return $text;
266 }
267
268 /**
269 * convert text to all supported variants
270 *
271 * @param string $text the text to be converted
272 * @return array of string
273 * @public
274 */
275 function autoConvertToAllVariants($text) {
276 $fname="LanguageConverter::autoConvertToAllVariants";
277 wfProfileIn( $fname );
278 if( !$this->mTablesLoaded )
279 $this->loadTables();
280
281 $ret = array();
282 foreach($this->mVariants as $variant) {
283 $ret[$variant] = $this->translate($text, $variant);
284 }
285
286 wfProfileOut( $fname );
287 return $ret;
288 }
289
290 /**
291 * convert link text to all supported variants
292 *
293 * @param string $text the text to be converted
294 * @return array of string
295 * @public
296 */
297 function convertLinkToAllVariants($text) {
298 if( !$this->mTablesLoaded )
299 $this->loadTables();
300
301 $ret = array();
302 $tarray = explode($this->mMarkup['begin'], $text);
303 $tfirst = array_shift($tarray);
304
305 foreach($this->mVariants as $variant)
306 $ret[$variant] = $this->translate($tfirst,$variant);
307
308 foreach($tarray as $txt) {
309 $marked = explode($this->mMarkup['end'], $txt, 2);
310
311 foreach($this->mVariants as $variant){
312 $ret[$variant] .= $this->mMarkup['begin'].$marked[0].$this->mMarkup['end'];
313 if(array_key_exists(1, $marked))
314 $ret[$variant] .= $this->translate($marked[1],$variant);
315 }
316
317 }
318
319 return $ret;
320 }
321
322
323 /**
324 * apply manual conversion
325 * @private
326 */
327 function applyManualConv($convRule){
328 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
329 $title = $convRule->getTitle();
330 if($title){
331 $this->mTitleFromFlag = true;
332 $this->mTitleDisplay = $title;
333 }
334
335 //apply manual conversion table to global table
336 $convTable = $convRule->getConvTable();
337 $action = $convRule->getRulesAction();
338 foreach($convTable as $v=>$t) {
339 if( !in_array($v,$this->mVariants) )continue;
340 if( $action=="add" )
341 $this->mTables[$v]->mergeArray($t);
342 elseif ( $action=="remove" )
343 $this->mTables[$v]->removeArray($t);
344 }
345 }
346
347 /**
348 * Convert text using a parser object for context
349 * @public
350 */
351 function parserConvert( $text, &$parser ) {
352 global $wgDisableLangConversion;
353 /* don't do anything if this is the conversion table */
354 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI &&
355 strpos($parser->mTitle->getText(), "Conversiontable") !== false )
356 {
357 return $text;
358 }
359
360 if($wgDisableLangConversion)
361 return $text;
362
363 $text = $this->convert( $text );
364 $parser->mOutput->setTitleText( $this->mTitleDisplay );
365 return $text;
366 }
367
368 /**
369 * convert title
370 * @private
371 */
372 function convertTitle($text){
373 // check for __NOTC__ tag
374 if( !$this->mDoTitleConvert ) {
375 $this->mTitleDisplay = $text;
376 return $text;
377 }
378
379 // use the title from the T flag if any
380 if($this->mTitleFromFlag){
381 $this->mTitleFromFlag = false;
382 return $this->mTitleDisplay;
383 }
384
385 global $wgRequest;
386 $isredir = $wgRequest->getText( 'redirect', 'yes' );
387 $action = $wgRequest->getText( 'action' );
388 if ( $isredir == 'no' || $action == 'edit' ) {
389 return $text;
390 } else {
391 $this->mTitleDisplay = $this->convert($text);
392 return $this->mTitleDisplay;
393 }
394 }
395
396 /**
397 * convert text to different variants of a language. the automatic
398 * conversion is done in autoConvert(). here we parse the text
399 * marked with -{}-, which specifies special conversions of the
400 * text that can not be accomplished in autoConvert()
401 *
402 * syntax of the markup:
403 * -{code1:text1;code2:text2;...}- or
404 * -{flags|code1:text1;code2:text2;...}- or
405 * -{text}- in which case no conversion should take place for text
406 *
407 * @param string $text text to be converted
408 * @param bool $isTitle whether this conversion is for the article title
409 * @return string converted text
410 * @public
411 */
412 function convert( $text , $isTitle=false) {
413
414 $mw =& MagicWord::get( 'notitleconvert' );
415 if( $mw->matchAndRemove( $text ) )
416 $this->mDoTitleConvert = false;
417 $mw =& MagicWord::get( 'nocontentconvert' );
418 if( $mw->matchAndRemove( $text ) ) {
419 $this->mDoContentConvert = false;
420 }
421
422 // no conversion if redirecting
423 $mw =& MagicWord::get( 'redirect' );
424 if( $mw->matchStart( $text ))
425 return $text;
426
427 // for title convertion
428 if ($isTitle) return $this->convertTitle($text);
429
430 $plang = $this->getPreferredVariant();
431 $tarray = explode($this->mMarkup['end'], $text);
432 $text = '';
433 foreach($tarray as $txt) {
434 $marked = explode($this->mMarkup['begin'], $txt, 2);
435
436 if( $this->mDoContentConvert )
437 $text .= $this->autoConvert($marked[0],$plang);
438 else
439 $text .= $marked[0];
440
441 if(array_key_exists(1, $marked)){
442 // strip the flags from syntax like -{T| ... }-
443 $crule = new ConverterRule($marked[1], $this);
444 $crule->parse($plang);
445
446 $text .= $crule->getDisplay();
447 $this->applyManualConv($crule);
448 }
449 }
450
451 return $text;
452 }
453
454 /**
455 * if a language supports multiple variants, it is
456 * possible that non-existing link in one variant
457 * actually exists in another variant. this function
458 * tries to find it. See e.g. LanguageZh.php
459 *
460 * @param string $link the name of the link
461 * @param mixed $nt the title object of the link
462 * @return null the input parameters may be modified upon return
463 * @public
464 */
465 function findVariantLink( &$link, &$nt ) {
466 global $wgDisableLangConversion;
467 $linkBatch = new LinkBatch();
468
469 $ns=NS_MAIN;
470
471 if(is_object($nt))
472 $ns = $nt->getNamespace();
473
474 $variants = $this->autoConvertToAllVariants($link);
475 if($variants == false) //give up
476 return;
477
478 $titles = array();
479
480 foreach( $variants as $v ) {
481 if($v != $link){
482 $varnt = Title::newFromText( $v, $ns );
483 if(!is_null($varnt)){
484 $linkBatch->addObj($varnt);
485 $titles[]=$varnt;
486 }
487 }
488 }
489
490 // fetch all variants in single query
491 $linkBatch->execute();
492
493 foreach( $titles as $varnt ) {
494 if( $varnt->getArticleID() > 0 ) {
495 $nt = $varnt;
496 if( !$wgDisableLangConversion )
497 $link = $v;
498 break;
499 }
500 }
501 }
502
503 /**
504 * returns language specific hash options
505 *
506 * @public
507 */
508 function getExtraHashOptions() {
509 $variant = $this->getPreferredVariant();
510 return '!' . $variant ;
511 }
512
513 /**
514 * get title text as defined in the body of the article text
515 *
516 * @public
517 */
518 function getParsedTitle() {
519 return $this->mTitleDisplay;
520 }
521
522 /**
523 * a write lock to the cache
524 *
525 * @private
526 */
527 function lockCache() {
528 global $wgMemc;
529 $success = false;
530 for($i=0; $i<30; $i++) {
531 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
532 break;
533 sleep(1);
534 }
535 return $success;
536 }
537
538 /**
539 * unlock cache
540 *
541 * @private
542 */
543 function unlockCache() {
544 global $wgMemc;
545 $wgMemc->delete($this->mCacheKey . "lock");
546 }
547
548
549 /**
550 * Load default conversion tables
551 * This method must be implemented in derived class
552 *
553 * @private
554 */
555 function loadDefaultTables() {
556 $name = get_class($this);
557 wfDie("Must implement loadDefaultTables() method in class $name");
558 }
559
560 /**
561 * load conversion tables either from the cache or the disk
562 * @private
563 */
564 function loadTables($fromcache=true) {
565 global $wgMemc;
566 if( $this->mTablesLoaded )
567 return;
568 wfProfileIn( __METHOD__ );
569 $this->mTablesLoaded = true;
570 $this->mTables = false;
571 if($fromcache) {
572 wfProfileIn( __METHOD__.'-cache' );
573 $this->mTables = $wgMemc->get( $this->mCacheKey );
574 wfProfileOut( __METHOD__.'-cache' );
575 }
576 if ( !$this->mTables || !isset( $this->mTables[self::CACHE_VERSION_KEY] ) ) {
577 wfProfileIn( __METHOD__.'-recache' );
578 // not in cache, or we need a fresh reload.
579 // we will first load the default tables
580 // then update them using things in MediaWiki:Zhconversiontable/*
581 $this->loadDefaultTables();
582 foreach($this->mVariants as $var) {
583 $cached = $this->parseCachedTable($var);
584 $this->mTables[$var]->mergeArray($cached);
585 }
586
587 $this->postLoadTables();
588 $this->mTables[self::CACHE_VERSION_KEY] = true;
589
590 if($this->lockCache()) {
591 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
592 $this->unlockCache();
593 }
594 wfProfileOut( __METHOD__.'-recache' );
595 }
596 wfProfileOut( __METHOD__ );
597 }
598
599 /**
600 * Hook for post processig after conversion tables are loaded
601 *
602 */
603 function postLoadTables() {}
604
605 /**
606 * Reload the conversion tables
607 *
608 * @private
609 */
610 function reloadTables() {
611 if($this->mTables)
612 unset($this->mTables);
613 $this->mTablesLoaded = false;
614 $this->loadTables(false);
615 }
616
617
618 /**
619 * parse the conversion table stored in the cache
620 *
621 * the tables should be in blocks of the following form:
622 * -{
623 * word => word ;
624 * word => word ;
625 * ...
626 * }-
627 *
628 * to make the tables more manageable, subpages are allowed
629 * and will be parsed recursively if $recursive=true
630 *
631 */
632 function parseCachedTable($code, $subpage='', $recursive=true) {
633 global $wgMessageCache;
634 static $parsed = array();
635
636 if(!is_object($wgMessageCache))
637 return array();
638
639 $key = 'Conversiontable/'.$code;
640 if($subpage)
641 $key .= '/' . $subpage;
642
643 if(array_key_exists($key, $parsed))
644 return array();
645
646 if ( strpos( $code, '/' ) === false ) {
647 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
648 } else {
649 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Conversiontable/$code" );
650 if ( $title && $title->exists() ) {
651 $article = new Article( $title );
652 $txt = $article->getContents();
653 } else {
654 $txt = '';
655 }
656 }
657
658 // get all subpage links of the form
659 // [[MediaWiki:conversiontable/zh-xx/...|...]]
660 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
661 $subs = explode('[[', $txt);
662 $sublinks = array();
663 foreach( $subs as $sub ) {
664 $link = explode(']]', $sub, 2);
665 if(count($link) != 2)
666 continue;
667 $b = explode('|', $link[0]);
668 $b = explode('/', trim($b[0]), 3);
669 if(count($b)==3)
670 $sublink = $b[2];
671 else
672 $sublink = '';
673
674 if($b[0] == $linkhead && $b[1] == $code) {
675 $sublinks[] = $sublink;
676 }
677 }
678
679
680 // parse the mappings in this page
681 $blocks = explode($this->mMarkup['begin'], $txt);
682 array_shift($blocks);
683 $ret = array();
684 foreach($blocks as $block) {
685 $mappings = explode($this->mMarkup['end'], $block, 2);
686 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
687 $table = explode( ';', $stripped );
688 foreach( $table as $t ) {
689 $m = explode( '=>', $t );
690 if( count( $m ) != 2)
691 continue;
692 // trim any trailling comments starting with '//'
693 $tt = explode('//', $m[1], 2);
694 $ret[trim($m[0])] = trim($tt[0]);
695 }
696 }
697 $parsed[$key] = true;
698
699
700 // recursively parse the subpages
701 if($recursive) {
702 foreach($sublinks as $link) {
703 $s = $this->parseCachedTable($code, $link, $recursive);
704 $ret = array_merge($ret, $s);
705 }
706 }
707
708 if ($this->mUcfirst) {
709 foreach ($ret as $k => $v) {
710 $ret[Language::ucfirst($k)] = Language::ucfirst($v);
711 }
712 }
713 return $ret;
714 }
715
716 /**
717 * Enclose a string with the "no conversion" tag. This is used by
718 * various functions in the Parser
719 *
720 * @param string $text text to be tagged for no conversion
721 * @return string the tagged text
722 * @public
723 */
724 function markNoConversion($text, $noParse=false) {
725 # don't mark if already marked
726 if(strpos($text, $this->mMarkup['begin']) ||
727 strpos($text, $this->mMarkup['end']))
728 return $text;
729
730 $ret = $this->mMarkup['begin'] .'R|'. $text . $this->mMarkup['end'];
731 return $ret;
732 }
733
734 /**
735 * convert the sorting key for category links. this should make different
736 * keys that are variants of each other map to the same key
737 */
738 function convertCategoryKey( $key ) {
739 return $key;
740 }
741 /**
742 * hook to refresh the cache of conversion tables when
743 * MediaWiki:conversiontable* is updated
744 * @private
745 */
746 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
747 $titleobj = $article->getTitle();
748 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
749 $title = $titleobj->getDBkey();
750 $t = explode('/', $title, 3);
751 $c = count($t);
752 if( $c > 1 && $t[0] == 'Conversiontable' ) {
753 if(in_array($t[1], $this->mVariants)) {
754 $this->reloadTables();
755 }
756 }
757 }
758 return true;
759 }
760
761 /**
762 * Armour rendered math against conversion
763 * Wrap math into rawoutput -{R| math }- syntax
764 * @public
765 */
766 function armourMath($text){
767 $ret = $this->mMarkup['begin'] . 'R|' . $text . $this->mMarkup['end'];
768 return $ret;
769 }
770 }
771
772 /**
773 * parser for rules of language conversion , parse rules in -{ }- tag
774 * @ingroup Language
775 * @author fdcn <fdcn64@gmail.com>
776 */
777 class ConverterRule {
778 var $mText; // original text in -{text}-
779 var $mConverter; // LanguageConverter object
780 var $mManualCodeError='<strong class="error">code error!</strong>';
781 var $mRuleDisplay = '',$mRuleTitle=false;
782 var $mRules = '';// string : the text of the rules
783 var $mRulesAction = 'none';
784 var $mFlags = array();
785 var $mConvTable = array();
786 var $mBidtable = array();// array of the translation in each variant
787 var $mUnidtable = array();// array of the translation in each variant
788
789 /**
790 * Constructor
791 *
792 * @param string $text the text between -{ and }-
793 * @param object $converter a LanguageConverter object
794 * @access public
795 */
796 function __construct($text,$converter){
797 $this->mText = $text;
798 $this->mConverter=$converter;
799 foreach($converter->mVariants as $v){
800 $this->mConvTable[$v]=array();
801 }
802 }
803
804 /**
805 * check if variants array in convert array
806 *
807 * @param string $variant Variant language code
808 * @return string Translated text
809 * @public
810 */
811 function getTextInBidtable($variants){
812 if(is_string($variants)){ $variants=array($variants); }
813 if(!is_array($variants)) return false;
814 foreach ($variants as $variant){
815 if(array_key_exists($variant, $this->mBidtable)){
816 return $this->mBidtable[$variant];
817 }
818 }
819 return false;
820 }
821
822 /**
823 * Parse flags with syntax -{FLAG| ... }-
824 * @private
825 */
826 function parseFlags(){
827 $text = $this->mText;
828 if(strlen($text) < 2 ) {
829 $this->mFlags = array( 'R' );
830 $this->mRules = $text;
831 return;
832 }
833
834 $flags = array();
835 $markup = $this->mConverter->mMarkup;
836 $validFlags = $this->mConverter->mFlags;
837
838 $tt = explode($markup['flagsep'], $text, 2);
839 if(count($tt) == 2) {
840 $f = explode($markup['varsep'], $tt[0]);
841 foreach($f as $ff) {
842 $ff = trim($ff);
843 if(array_key_exists($ff, $validFlags) &&
844 !in_array($validFlags[$ff], $flags))
845 $flags[] = $validFlags[$ff];
846 }
847 $rules = $tt[1];
848 } else {
849 $rules = $text;
850 }
851
852 //check flags
853 if( in_array('R',$flags) ){
854 $flags = array('R');// remove other flags
855 } elseif ( in_array('N',$flags) ){
856 $flags = array('N');// remove other flags
857 } elseif ( in_array('-',$flags) ){
858 $flags = array('-');// remove other flags
859 } elseif (count($flags)==1 && $flags[0]=='T'){
860 $flags[]='H';
861 } elseif ( in_array('H',$flags) ){
862 // replace A flag, and remove other flags except T
863 $temp=array('+','H');
864 if(in_array('T',$flags)) $temp[] = 'T';
865 if(in_array('D',$flags)) $temp[] = 'D';
866 $flags = $temp;
867 } else {
868 if ( in_array('A',$flags)) {
869 $flags[]='+';
870 $flags[]='S';
871 }
872 if ( in_array('D',$flags) )
873 $flags=array_diff($flags,array('S'));
874 }
875 if ( count($flags)==0 )
876 $flags = array('S');
877 $this->mRules=$rules;
878 $this->mFlags=$flags;
879 }
880
881 /**
882 * generate conversion table
883 * @private
884 */
885 function parseRules() {
886 $rules = $this->mRules;
887 $flags = $this->mFlags;
888 $bidtable = array();
889 $unidtable = array();
890 $markup = $this->mConverter->mMarkup;
891
892 $choice = explode($markup['varsep'], $rules );
893 foreach($choice as $c) {
894 $v = explode($markup['codesep'], $c);
895 if(count($v) != 2)
896 continue;// syntax error, skip
897 $to=trim($v[1]);
898 $v=trim($v[0]);
899 $u = explode($markup['unidsep'], $v);
900 if(count($u) == 1) {
901 $bidtable[$v] = $to;
902 } else if(count($u) == 2){
903 $from=trim($u[0]);$v=trim($u[1]);
904 if( array_key_exists($v,$unidtable) && !is_array($unidtable[$v]) )
905 $unidtable[$v]=array($from=>$to);
906 else
907 $unidtable[$v][$from]=$to;
908 }
909 // syntax error, pass
910 if (!array_key_exists($v,$this->mConverter->mVariantNames)){
911 $bidtable = array();
912 $unidtable = array();
913 break;
914 }
915 }
916 $this->mBidtable = $bidtable;
917 $this->mUnidtable = $unidtable;
918 }
919
920 /**
921 * @private
922 */
923 function getRulesDesc(){
924 $codesep = $this->mConverter->mDescCodeSep;
925 $varsep = $this->mConverter->mDescVarSep;
926 $text='';
927 foreach($this->mBidtable as $k => $v)
928 $text .= $this->mConverter->mVariantNames[$k]."$codesep$v$varsep";
929 foreach($this->mUnidtable as $k => $a)
930 foreach($a as $from=>$to)
931 $text.=$from.'⇒'.$this->mConverter->mVariantNames[$k]."$codesep$to$varsep";
932 return $text;
933 }
934
935 /**
936 * Parse rules conversion
937 * @private
938 */
939 function getRuleConvertedStr($variant,$doConvert){
940 $bidtable = $this->mBidtable;
941 $unidtable = $this->mUnidtable;
942
943 if( count($bidtable) + count($unidtable) == 0 ){
944 return $this->mRules;
945 } elseif ($doConvert){// the text converted
946 // display current variant in bidirectional array
947 $disp = $this->getTextInBidtable($variant);
948 // or display current variant in fallbacks
949 if(!$disp)
950 $disp = $this->getTextInBidtable(
951 $this->mConverter->getVariantFallbacks($variant));
952 // or display current variant in unidirectional array
953 if(!$disp && array_key_exists($variant,$unidtable)){
954 $disp = array_values($unidtable[$variant]);
955 $disp = $disp[0];
956 }
957 // or display frist text under disable manual convert
958 if(!$disp && $this->mConverter->mManualLevel[$variant]=='disable') {
959 if(count($bidtable)>0){
960 $disp = array_values($bidtable);
961 $disp = $disp[0];
962 } else {
963 $disp = array_values($unidtable);
964 $disp = array_values($disp[0]);
965 $disp = $disp[0];
966 }
967 }
968 return $disp;
969 } else {// no convert
970 return $this->mRules;
971 }
972 }
973
974 /**
975 * generate conversion table for all text
976 * @private
977 */
978 function generateConvTable(){
979 $flags = $this->mFlags;
980 $bidtable = $this->mBidtable;
981 $unidtable = $this->mUnidtable;
982 $manLevel = $this->mConverter->mManualLevel;
983
984 $vmarked=array();
985 foreach($this->mConverter->mVariants as $v) {
986 /* for bidirectional array
987 fill in the missing variants, if any,
988 with fallbacks */
989 if(!array_key_exists($v, $bidtable)) {
990 $variantFallbacks = $this->mConverter->getVariantFallbacks($v);
991 $vf = $this->getTextInBidtable($variantFallbacks);
992 if($vf) $bidtable[$v] = $vf;
993 }
994
995 if(array_key_exists($v,$bidtable)){
996 foreach($vmarked as $vo){
997 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
998 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
999 // to introduce a custom mapping between
1000 // words WordZh and WordTw in the whole text
1001 if($manLevel[$v]=='bidirectional'){
1002 $this->mConvTable[$v][$bidtable[$vo]]=$bidtable[$v];
1003 }
1004 if($manLevel[$vo]=='bidirectional'){
1005 $this->mConvTable[$vo][$bidtable[$v]]=$bidtable[$vo];
1006 }
1007 }
1008 $vmarked[]=$v;
1009 }
1010 /*for unidirectional array
1011 fill to convert tables */
1012 $allow_unid = $manLevel[$v]=='bidirectional'
1013 || $manLevel[$v]=='unidirectional';
1014 if($allow_unid && array_key_exists($v,$unidtable)){
1015 $ct=$this->mConvTable[$v];
1016 $this->mConvTable[$v] = array_merge($ct,$unidtable[$v]);
1017 }
1018 }
1019 }
1020
1021 /**
1022 * Parse rules and flags
1023 * @public
1024 */
1025 function parse($variant){
1026 if(!$variant) $variant = $this->mConverter->getPreferredVariant();
1027
1028 $this->parseFlags();
1029 $flags = $this->mFlags;
1030
1031 if( !in_array('R',$flags) || !in_array('N',$flags) ){
1032 //FIXME: may cause trouble here...
1033 //strip &nbsp; since it interferes with the parsing, plus,
1034 //all spaces should be stripped in this tag anyway.
1035 $this->mRules = str_replace('&nbsp;', '', $this->mRules);
1036 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1037 $this->mRules = str_replace('=&gt;','=>',$this->mRules);
1038
1039 $this->parseRules();
1040 }
1041 $rules = $this->mRules;
1042
1043 if(count($this->mBidtable)==0 && count($this->mUnidtable)==0){
1044 if(in_array('+',$flags) || in_array('-',$flags))
1045 // fill all variants if text in -{A/H/-|text} without rules
1046 foreach($this->mConverter->mVariants as $v)
1047 $this->mBidtable[$v] = $rules;
1048 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1049 $this->mFlags = $flags = array('R');
1050 }
1051
1052 if( in_array('R',$flags) ) {
1053 // if we don't do content convert, still strip the -{}- tags
1054 $this->mRuleDisplay = $rules;
1055 } elseif ( in_array('N',$flags) ){
1056 // proces N flag: output current variant name
1057 $this->mRuleDisplay = $this->mConverter->mVariantNames[trim($rules)];
1058 } elseif ( in_array('D',$flags) ){
1059 // proces D flag: output rules description
1060 $this->mRuleDisplay = $this->getRulesDesc();
1061 } elseif ( in_array('H',$flags) || in_array('-',$flags) ) {
1062 // proces H,- flag or T only: output nothing
1063 $this->mRuleDisplay = '';
1064 } elseif ( in_array('S',$flags) ){
1065 $this->mRuleDisplay = $this->getRuleConvertedStr($variant,
1066 $this->mConverter->mDoContentConvert);
1067 } else {
1068 $this->mRuleDisplay= $this->mManualCodeError;
1069 }
1070 // proces T flag
1071 if ( in_array('T',$flags) ) {
1072 $this->mRuleTitle = $this->getRuleConvertedStr($variant,
1073 $this->mConverter->mDoTitleConvert);
1074 }
1075
1076 if (in_array('-', $flags))
1077 $this->mRulesAction='remove';
1078 if (in_array('+', $flags))
1079 $this->mRulesAction='add';
1080
1081 $this->generateConvTable();
1082 }
1083
1084 /**
1085 * @public
1086 */
1087 function hasRules(){
1088 // TODO:
1089 }
1090
1091 /**
1092 * get display text on markup -{...}-
1093 * @public
1094 */
1095 function getDisplay(){
1096 return $this->mRuleDisplay;
1097 }
1098 /**
1099 * get converted title
1100 * @public
1101 */
1102 function getTitle(){
1103 return $this->mRuleTitle;
1104 }
1105
1106 /**
1107 * return how deal with conversion rules
1108 * @public
1109 */
1110 function getRulesAction(){
1111 return $this->mRulesAction;
1112 }
1113
1114 /**
1115 * get conversion table ( bidirectional and unidirectional conversion table )
1116 * @public
1117 */
1118 function getConvTable(){
1119 return $this->mConvTable;
1120 }
1121
1122 /**
1123 * get conversion rules string
1124 * @public
1125 */
1126 function getRules(){
1127 return $this->mRules;
1128 }
1129
1130 /**
1131 * get conversion flags
1132 * @public
1133 */
1134 function getFlags(){
1135 return $this->mFlags;
1136 }
1137 }