* (bug 14604) Update LanguageConverter for compatibility on -{*|xxx}- usage
[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 * @public
46 */
47 function __construct($langobj, $maincode,
48 $variants=array(),
49 $variantfallbacks=array(),
50 $markup=array(),
51 $flags = array(),
52 $manualLevel = array() ) {
53 $this->mLangObj = $langobj;
54 $this->mMainLanguageCode = $maincode;
55 $this->mVariants = $variants;
56 $this->mVariantFallbacks = $variantfallbacks;
57 global $wgLanguageNames;
58 $this->mVariantNames = $wgLanguageNames;
59 $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
60 $m = array(
61 'begin'=>'-{',
62 'flagsep'=>'|',
63 'unidsep'=>'=>', //for unidirectional conversion
64 'codesep'=>':',
65 'varsep'=>';',
66 'end'=>'}-'
67 );
68 $this->mMarkup = array_merge($m, $markup);
69 $f = array(
70 // 'S' show converted text
71 // '+' add rules for alltext
72 // 'E' the gave flags is error
73 // these flags above are reserved for program
74 'A'=>'A', // add rule for convert code (all text convert)
75 'T'=>'T', // title convert
76 'R'=>'R', // raw content
77 'D'=>'D', // convert description (subclass implement)
78 '-'=>'-', // remove convert (not implement)
79 'H'=>'H', // add rule for convert code (but no display in placed code )
80 'N'=>'N' // current variant name
81 );
82 $this->mFlags = array_merge($f, $flags);
83 foreach( $this->mVariants as $v)
84 $this->mManualLevel[$v]=array_key_exists($v,$manualLevel)
85 ?$manualLevel[$v]
86 :'bidirectional';
87 }
88
89 /**
90 * @public
91 */
92 function getVariants() {
93 return $this->mVariants;
94 }
95
96 /**
97 * in case some variant is not defined in the markup, we need
98 * to have some fallback. for example, in zh, normally people
99 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
100 * when zh-sg is preferred but not defined, we will pick zh-hans
101 * in this case. right now this is only used by zh.
102 *
103 * @param string $v the language code of the variant
104 * @return string array the code of the fallback language or false if there is no fallback
105 * @public
106 */
107 function getVariantFallbacks($v) {
108 if( isset( $this->mVariantFallbacks[$v] ) ) {
109 return $this->mVariantFallbacks[$v];
110 }
111 return $this->mMainLanguageCode;
112 }
113
114 /**
115 * get preferred language variants.
116 * @param boolean $fromUser Get it from $wgUser's preferences
117 * @return string the preferred language code
118 * @public
119 */
120 function getPreferredVariant( $fromUser = true ) {
121 global $wgUser, $wgRequest, $wgVariantArticlePath, $wgDefaultLanguageVariant;
122
123 if($this->mPreferredVariant)
124 return $this->mPreferredVariant;
125
126 // see if the preference is set in the request
127 $req = $wgRequest->getText( 'variant' );
128 if( in_array( $req, $this->mVariants ) ) {
129 $this->mPreferredVariant = $req;
130 return $req;
131 }
132
133 // check the syntax /code/ArticleTitle
134 if($wgVariantArticlePath!=false && isset($_SERVER['SCRIPT_NAME'])){
135 // Note: SCRIPT_NAME probably won't hold the correct value if PHP is run as CGI
136 // (it will hold path to php.cgi binary), and might not exist on some very old PHP installations
137 $scriptBase = basename( $_SERVER['SCRIPT_NAME'] );
138 if(in_array($scriptBase,$this->mVariants)){
139 $this->mPreferredVariant = $scriptBase;
140 return $this->mPreferredVariant;
141 }
142 }
143
144 // get language variant preference from logged in users
145 // Don't call this on stub objects because that causes infinite
146 // recursion during initialisation
147 if( $fromUser && $wgUser->isLoggedIn() ) {
148 $this->mPreferredVariant = $wgUser->getOption('variant');
149 return $this->mPreferredVariant;
150 }
151
152 // see if default variant is globaly set
153 if($wgDefaultLanguageVariant != false && in_array( $wgDefaultLanguageVariant, $this->mVariants )){
154 $this->mPreferredVariant = $wgDefaultLanguageVariant;
155 return $this->mPreferredVariant;
156 }
157
158 # FIXME rewrite code for parsing http header. The current code
159 # is written specific for detecting zh- variants
160 if( !$this->mPreferredVariant ) {
161 // see if some supported language variant is set in the
162 // http header, but we don't set the mPreferredVariant
163 // variable in case this is called before the user's
164 // preference is loaded
165 $pv=$this->mMainLanguageCode;
166 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
167 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
168 $zh = strstr($header, $pv.'-');
169 if($zh) {
170 $pv = substr($zh,0,5);
171 }
172 }
173 // don't try to return bad variant
174 if(in_array( $pv, $this->mVariants ))
175 return $pv;
176 }
177
178 return $this->mMainLanguageCode;
179
180 }
181
182 /**
183 * dictionary-based conversion
184 *
185 * @param string $text the text to be converted
186 * @param string $toVariant the target language code
187 * @return string the converted text
188 * @private
189 */
190 function autoConvert($text, $toVariant=false) {
191 $fname="LanguageConverter::autoConvert";
192
193 wfProfileIn( $fname );
194
195 if(!$this->mTablesLoaded)
196 $this->loadTables();
197
198 if(!$toVariant)
199 $toVariant = $this->getPreferredVariant();
200 if(!in_array($toVariant, $this->mVariants))
201 return $text;
202
203 /* we convert everything except:
204 1. html markups (anything between < and >)
205 2. html entities
206 3. place holders created by the parser
207 */
208 global $wgParser;
209 if (isset($wgParser) && $wgParser->UniqPrefix()!=''){
210 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
211 } else
212 $marker = "";
213
214 // this one is needed when the text is inside an html markup
215 $htmlfix = '|<[^>]+$|^[^<>]*>';
216
217 // disable convert to variants between <code></code> tags
218 $codefix = '<code>.+?<\/code>|';
219 // disable convertsion of <script type="text/javascript"> ... </script>
220 $scriptfix = '<script.*?>.*?<\/script>|';
221 // disable conversion of <pre xxxx> ... </pre>
222 $prefix = '<pre.*?>.*?<\/pre>|';
223
224 $reg = '/'.$codefix . $scriptfix . $prefix . '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
225
226 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE);
227
228 $m = array_shift($matches);
229
230 $ret = $this->translate($m[0], $toVariant);
231 $mstart = $m[1]+strlen($m[0]);
232 foreach($matches as $m) {
233 $ret .= substr($text, $mstart, $m[1]-$mstart);
234 $ret .= $this->translate($m[0], $toVariant);
235 $mstart = $m[1] + strlen($m[0]);
236 }
237 wfProfileOut( $fname );
238 return $ret;
239 }
240
241 /**
242 * Translate a string to a variant
243 * Doesn't process markup or do any of that other stuff, for that use convert()
244 *
245 * @param string $text Text to convert
246 * @param string $variant Variant language code
247 * @return string Translated text
248 * @private
249 */
250 function translate( $text, $variant ) {
251 wfProfileIn( __METHOD__ );
252 if( !$this->mTablesLoaded )
253 $this->loadTables();
254 $text = $this->mTables[$variant]->replace( $text );
255 wfProfileOut( __METHOD__ );
256 return $text;
257 }
258
259 /**
260 * convert text to all supported variants
261 *
262 * @param string $text the text to be converted
263 * @return array of string
264 * @public
265 */
266 function autoConvertToAllVariants($text) {
267 $fname="LanguageConverter::autoConvertToAllVariants";
268 wfProfileIn( $fname );
269 if( !$this->mTablesLoaded )
270 $this->loadTables();
271
272 $ret = array();
273 foreach($this->mVariants as $variant) {
274 $ret[$variant] = $this->translate($text, $variant);
275 }
276
277 wfProfileOut( $fname );
278 return $ret;
279 }
280
281 /**
282 * convert link text to all supported variants
283 *
284 * @param string $text the text to be converted
285 * @return array of string
286 * @public
287 */
288 function convertLinkToAllVariants($text) {
289 if( !$this->mTablesLoaded )
290 $this->loadTables();
291
292 $ret = array();
293 $tarray = explode($this->mMarkup['begin'], $text);
294 $tfirst = array_shift($tarray);
295
296 foreach($this->mVariants as $variant)
297 $ret[$variant] = $this->translate($tfirst,$variant);
298
299 foreach($tarray as $txt) {
300 $marked = explode($this->mMarkup['end'], $txt, 2);
301
302 foreach($this->mVariants as $variant){
303 $ret[$variant] .= $this->mMarkup['begin'].$marked[0].$this->mMarkup['end'];
304 if(array_key_exists(1, $marked))
305 $ret[$variant] .= $this->translate($marked[1],$variant);
306 }
307
308 }
309
310 return $ret;
311 }
312
313
314 /**
315 * apply manual conversion
316 * @private
317 */
318 function applyManualConv($convRule){
319 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom conversion in title
320 $title = $convRule->getTitle();
321 if($title){
322 $this->mTitleFromFlag = true;
323 $this->mTitleDisplay = $title;
324 }
325
326 //add manual conversion table to global table
327 $convTable = $convRule->getConvTable();
328 $isAdd = $convRule->getRulesAction()=="add";
329 $isRemove = $convRule->getRulesAction()=="remove";
330 foreach($convTable as $v=>$t) {
331 if( !in_array($v,$this->mVariants) )continue;
332 if( $isAdd )
333 $this->mTables[$v]->mergeArray($t);
334 elseif ( $isRemove )
335 $this->mTables[$v]->removeArray($t);
336 }
337 }
338
339 /**
340 * Convert text using a parser object for context
341 * @public
342 */
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 )
348 {
349 return $text;
350 }
351
352 if($wgDisableLangConversion)
353 return $text;
354
355 $text = $this->convert( $text );
356 $parser->mOutput->setTitleText( $this->mTitleDisplay );
357 return $text;
358 }
359
360 /**
361 * convert title
362 * @private
363 */
364 function convertTitle($text){
365 // check for __NOTC__ tag
366 if( !$this->mDoTitleConvert ) {
367 $this->mTitleDisplay = $text;
368 return $text;
369 }
370
371 // use the title from the T flag if any
372 if($this->mTitleFromFlag){
373 $this->mTitleFromFlag = false;
374 return $this->mTitleDisplay;
375 }
376
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;
385 }
386 }
387
388 /**
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()
393 *
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
398 *
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
403 */
404 function convert( $text , $isTitle=false) {
405
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;
412 }
413
414 // no conversion if redirecting
415 $mw =& MagicWord::get( 'redirect' );
416 if( $mw->matchStart( $text ))
417 return $text;
418
419 // for title convertion
420 if ($isTitle) return $this->convertTitle($text);
421
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);
427
428 if( $this->mDoContentConvert )
429 $text .= $this->autoConvert($marked[0],$plang);
430 else
431 $text .= $marked[0];
432
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);
437
438 $text .= $crule->getDisplay();
439 $this->applyManualConv($crule);
440 }
441 }
442
443 return $text;
444 }
445
446 /**
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
451 *
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
456 */
457 function findVariantLink( &$link, &$nt ) {
458 global $wgDisableLangConversion;
459 $linkBatch = new LinkBatch();
460
461 $ns=NS_MAIN;
462
463 if(is_object($nt))
464 $ns = $nt->getNamespace();
465
466 $variants = $this->autoConvertToAllVariants($link);
467 if($variants == false) //give up
468 return;
469
470 $titles = array();
471
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;
478 }
479 }
480 }
481
482 // fetch all variants in single query
483 $linkBatch->execute();
484
485 foreach( $titles as $varnt ) {
486 if( $varnt->getArticleID() > 0 ) {
487 $nt = $varnt;
488 if( !$wgDisableLangConversion )
489 $link = $v;
490 break;
491 }
492 }
493 }
494
495 /**
496 * returns language specific hash options
497 *
498 * @public
499 */
500 function getExtraHashOptions() {
501 $variant = $this->getPreferredVariant();
502 return '!' . $variant ;
503 }
504
505 /**
506 * get title text as defined in the body of the article text
507 *
508 * @public
509 */
510 function getParsedTitle() {
511 return $this->mTitleDisplay;
512 }
513
514 /**
515 * a write lock to the cache
516 *
517 * @private
518 */
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);
526 }
527 return $success;
528 }
529
530 /**
531 * unlock cache
532 *
533 * @private
534 */
535 function unlockCache() {
536 global $wgMemc;
537 $wgMemc->delete($this->mCacheKey . "lock");
538 }
539
540
541 /**
542 * Load default conversion tables
543 * This method must be implemented in derived class
544 *
545 * @private
546 */
547 function loadDefaultTables() {
548 $name = get_class($this);
549 wfDie("Must implement loadDefaultTables() method in class $name");
550 }
551
552 /**
553 * load conversion tables either from the cache or the disk
554 * @private
555 */
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' );
567 }
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);
577 }
578
579 $this->postLoadTables();
580 $this->mTables[self::CACHE_VERSION_KEY] = true;
581
582 if($this->lockCache()) {
583 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
584 $this->unlockCache();
585 }
586 wfProfileOut( __METHOD__.'-recache' );
587 }
588 wfProfileOut( __METHOD__ );
589 }
590
591 /**
592 * Hook for post processig after conversion tables are loaded
593 *
594 */
595 function postLoadTables() {}
596
597 /**
598 * Reload the conversion tables
599 *
600 * @private
601 */
602 function reloadTables() {
603 if($this->mTables)
604 unset($this->mTables);
605 $this->mTablesLoaded = false;
606 $this->loadTables(false);
607 }
608
609
610 /**
611 * parse the conversion table stored in the cache
612 *
613 * the tables should be in blocks of the following form:
614 * -{
615 * word => word ;
616 * word => word ;
617 * ...
618 * }-
619 *
620 * to make the tables more manageable, subpages are allowed
621 * and will be parsed recursively if $recursive=true
622 *
623 */
624 function parseCachedTable($code, $subpage='', $recursive=true) {
625 global $wgMessageCache;
626 static $parsed = array();
627
628 if(!is_object($wgMessageCache))
629 return array();
630
631 $key = 'Conversiontable/'.$code;
632 if($subpage)
633 $key .= '/' . $subpage;
634
635 if(array_key_exists($key, $parsed))
636 return array();
637
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 = '';
647 }
648 }
649
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 = '';
665
666 if($b[0] == $linkhead && $b[1] == $code) {
667 $sublinks[] = $sublink;
668 }
669 }
670
671
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]);
687 }
688 }
689 $parsed[$key] = true;
690
691
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);
697 }
698 }
699
700 if ($this->mUcfirst) {
701 foreach ($ret as $k => $v) {
702 $ret[Language::ucfirst($k)] = Language::ucfirst($v);
703 }
704 }
705 return $ret;
706 }
707
708 /**
709 * Enclose a string with the "no conversion" tag. This is used by
710 * various functions in the Parser
711 *
712 * @param string $text text to be tagged for no conversion
713 * @return string the tagged text
714 * @public
715 */
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;
721
722 $ret = $this->mMarkup['begin'] .'R|'. $text . $this->mMarkup['end'];
723 return $ret;
724 }
725
726 /**
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
729 */
730 function convertCategoryKey( $key ) {
731 return $key;
732 }
733 /**
734 * hook to refresh the cache of conversion tables when
735 * MediaWiki:conversiontable* is updated
736 * @private
737 */
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();
747 }
748 }
749 }
750 return true;
751 }
752
753 /**
754 * Armour rendered math against conversion
755 * Wrap math into rawoutput -{R| math }- syntax
756 * @public
757 */
758 function armourMath($text){
759 $ret = $this->mMarkup['begin'] . 'R|' . $text . $this->mMarkup['end'];
760 return $ret;
761 }
762 }
763
764 /**
765 * parser for rules of language conversion , parse rules in -{ }- tag
766 * @ingroup Language
767 * @author fdcn <fdcn64@gmail.com>
768 */
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
780
781 /**
782 * Constructor
783 *
784 * @param string $text the text between -{ and }-
785 * @param object $converter a LanguageConverter object
786 * @access public
787 */
788 function __construct($text,$converter){
789 $this->mText = $text;
790 $this->mConverter=$converter;
791 foreach($converter->mVariants as $v){
792 $this->mConvTable[$v]=array();
793 }
794 }
795
796 /**
797 * check if variants array in convert array
798 *
799 * @param string $variant Variant language code
800 * @return string Translated text
801 * @public
802 */
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];
809 }
810 }
811 return false;
812 }
813
814 /**
815 * Parse flags with syntax -{FLAG| ... }-
816 * @private
817 */
818 function parseFlags(){
819 $text = $this->mText;
820 if(strlen($text) < 2 ) {
821 $this->mFlags = array( 'R' );
822 $this->mRules = $text;
823 return;
824 }
825
826 $flags = array();
827 $markup = $this->mConverter->mMarkup;
828 $validFlags = $this->mConverter->mFlags;
829
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];
838 }
839 $rules = $tt[1];
840 } else {
841 $rules = $text;
842 }
843
844 if( !in_array('R',$flags) ){
845 //FIXME: may cause trouble here...
846 //strip &nbsp; since it interferes with the parsing, plus,
847 //all spaces should be stripped in this tag anyway.
848 $rules = str_replace('&nbsp;', '', $rules);
849 $rules = str_replace('=&gt;','=>',$rules);
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 //$rules = $this->mRules;
980 $flags = $this->mFlags;
981 $bidtable = $this->mBidtable;
982 $unidtable = $this->mUnidtable;
983 $manLevel = $this->mConverter->mManualLevel;
984
985 $vmarked=array();
986 foreach($this->mConverter->mVariants as $v) {
987 /* for bidirectional array
988 fill in the missing variants, if any,
989 with fallbacks */
990 if(!array_key_exists($v, $bidtable)) {
991 $variantFallbacks = $this->mConverter->getVariantFallbacks($v);
992 $vf = $this->getTextInBidtable($variantFallbacks);
993 if($vf) $bidtable[$v] = $vf;
994 }
995
996 if(array_key_exists($v,$bidtable)){
997 foreach($vmarked as $vo){
998 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
999 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
1000 // to introduce a custom mapping between
1001 // words WordZh and WordTw in the whole text
1002 if($manLevel[$v]=='bidirectional'){
1003 $this->mConvTable[$v][$bidtable[$vo]]=$bidtable[$v];
1004 }
1005 if($manLevel[$vo]=='bidirectional'){
1006 $this->mConvTable[$vo][$bidtable[$v]]=$bidtable[$vo];
1007 }
1008 }
1009 $vmarked[]=$v;
1010 }
1011 /*for unidirectional array
1012 fill to convert tables */
1013 $allow_unid = $manLevel[$v]=='bidirectional'
1014 || $manLevel[$v]=='unidirectional';
1015 if($allow_unid && array_key_exists($v,$unidtable)){
1016 $ct=$this->mConvTable[$v];
1017 $this->mConvTable[$v] = array_merge($ct,$unidtable[$v]);
1018 }
1019 }
1020 }
1021
1022 /**
1023 * Parse rules and flags
1024 * @public
1025 */
1026 function parse($variant){
1027 if(!$variant) $variant = $this->mConverter->getPreferredVariant();
1028
1029 $this->parseFlags();
1030 $this->parseRules();
1031
1032 $rules = $this->mRules;
1033 $flags = $this->mFlags;
1034
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');
1042 }
1043
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;
1061 }
1062 // proces T flag : output nothing
1063 if ( in_array('T',$flags) ) {
1064 $this->mRuleTitle = $this->getRuleConvertedStr($variant,
1065 $this->mConverter->mDoTitleConvert);
1066 }
1067
1068 if (in_array('-', $flags))
1069 $this->mRulesAction='remove';
1070 if (in_array('+', $flags))
1071 $this->mRulesAction='add';
1072
1073 $this->generateConvTable();
1074 }
1075
1076 /**
1077 * @public
1078 */
1079 function hasRules(){
1080 // TODO:
1081 }
1082
1083 /**
1084 * get display text on markup -{...}-
1085 * @param string $variant the current variant
1086 * @public
1087 */
1088 function getDisplay(){
1089 return $this->mRuleDisplay;
1090 }
1091 /**
1092 * get converted title
1093 * @param string $variant the current variant
1094 * @public
1095 */
1096 function getTitle(){
1097 return $this->mRuleTitle;
1098 }
1099
1100 /**
1101 * return how deal with conversion rules
1102 * @public
1103 */
1104 function getRulesAction(){
1105 return $this->mRulesAction;
1106 }
1107
1108 /**
1109 * get conversion table ( bidirectional and unidirectional conversion table )
1110 * @public
1111 */
1112 function getConvTable(){
1113 return $this->mConvTable;
1114 }
1115
1116 /**
1117 * get conversion rules string
1118 * @public
1119 */
1120 function getRules(){
1121 return $this->mRules;
1122 }
1123
1124 /**
1125 * get conversion flags
1126 * @public
1127 */
1128 function getFlags(){
1129 return $this->mFlags;
1130 }
1131 }