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