Move method 'getPreferredVariant' to Language class, patched by Fdcn.
[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 // more efficient than array_merge(), about 2.5 times.
300 $this->mManualAddTables[$v][$from] = $to;
301 }
302 }
303 elseif ( $action=="remove" )
304 $this->mManualRemoveTables[$v] = array_merge($this->mManualRemoveTables[$v], $t);
305 }
306 }
307
308 /**
309 * apply manual conversion from $this->mManualAddTables and $this->mManualRemoveTables
310 * @private
311 */
312 function applyManualConv(){
313 //apply manual conversion table to global table
314 foreach($this->mVariants as $v) {
315 if (count($this->mManualAddTables[$v]) > 0) {
316 $this->mTables[$v]->mergeArray($this->mManualAddTables[$v]);
317 }
318 if (count($this->mManualRemoveTables[$v]) > 0)
319 $this->mTables[$v]->removeArray($this->mManualRemoveTables[$v]);
320 }
321 }
322
323 /**
324 * Convert text using a parser object for context
325 * @public
326 */
327 function parserConvert( $text, &$parser ) {
328 global $wgDisableLangConversion;
329 /* don't do anything if this is the conversion table */
330 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI &&
331 strpos($parser->mTitle->getText(), "Conversiontable") !== false )
332 {
333 return $text;
334 }
335
336 if($wgDisableLangConversion)
337 return $text;
338
339 $text = $this->convert( $text );
340 $parser->mOutput->setTitleText( $this->mTitleDisplay );
341 return $text;
342 }
343
344 /**
345 * convert title
346 * @private
347 */
348 function convertTitle($text){
349 global $wgDisableTitleConversion, $wgUser;
350
351 // check for global param and __NOTC__ tag
352 if( $wgDisableTitleConversion || !$this->mDoTitleConvert || $wgUser->getOption('noconvertlink') == 1 ) {
353 $this->mTitleDisplay = $text;
354 return $text;
355 }
356
357 // use the title from the T flag if any
358 if($this->mTitleFromFlag){
359 $this->mTitleFromFlag = false;
360 return $this->mTitleDisplay;
361 }
362
363 global $wgRequest;
364 $isredir = $wgRequest->getText( 'redirect', 'yes' );
365 $action = $wgRequest->getText( 'action' );
366 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
367 if ( $isredir == 'no' || $action == 'edit' || $action == 'submit' || $linkconvert == 'no' ) {
368 return $text;
369 } else {
370 $this->mTitleDisplay = $this->convert($text);
371 return $this->mTitleDisplay;
372 }
373 }
374
375 /**
376 * convert text to different variants of a language. the automatic
377 * conversion is done in autoConvert(). here we parse the text
378 * marked with -{}-, which specifies special conversions of the
379 * text that can not be accomplished in autoConvert()
380 *
381 * syntax of the markup:
382 * -{code1:text1;code2:text2;...}- or
383 * -{flags|code1:text1;code2:text2;...}- or
384 * -{text}- in which case no conversion should take place for text
385 *
386 * @param string $text text to be converted
387 * @param bool $isTitle whether this conversion is for the article title
388 * @return string converted text
389 * @public
390 */
391 function convert( $text , $isTitle=false) {
392
393 $mw =& MagicWord::get( 'notitleconvert' );
394 if( $mw->matchAndRemove( $text ) )
395 $this->mDoTitleConvert = false;
396 $mw =& MagicWord::get( 'nocontentconvert' );
397 if( $mw->matchAndRemove( $text ) ) {
398 $this->mDoContentConvert = false;
399 }
400
401 // no conversion if redirecting
402 $mw =& MagicWord::get( 'redirect' );
403 if( $mw->matchStart( $text ))
404 return $text;
405
406 // for title convertion
407 if ($isTitle) return $this->convertTitle($text);
408
409 $plang = $this->getPreferredVariant();
410 $tarray = StringUtils::explode($this->mMarkup['end'], $text);
411 $text = '';
412
413 $marks = array();
414 foreach($tarray as $txt) {
415 $marked = explode($this->mMarkup['begin'], $txt, 2);
416 if (array_key_exists(1, $marked)) {
417 $crule = new ConverterRule($marked[1], $this);
418 $crule->parse($plang);
419 $marked[1] = $crule->getDisplay();
420 $this->prepareManualConv($crule);
421 }
422 else
423 $marked[0] .= $this->mMarkup['end'];
424 array_push($marks, $marked);
425 }
426 $this->applyManualConv();
427 foreach ($marks as $marked) {
428 if( $this->mDoContentConvert )
429 $text .= $this->autoConvert($marked[0],$plang);
430 else
431 $text .= $marked[0];
432 if( array_key_exists(1, $marked) )
433 $text .= $marked[1];
434 }
435 // Remove the last delimiter (wasn't real)
436 $text = substr( $text, 0, -strlen( $this->mMarkup['end'] ) );
437
438 return $text;
439 }
440
441 /**
442 * if a language supports multiple variants, it is
443 * possible that non-existing link in one variant
444 * actually exists in another variant. this function
445 * tries to find it. See e.g. LanguageZh.php
446 *
447 * @param string $link the name of the link
448 * @param mixed $nt the title object of the link
449 * @return null the input parameters may be modified upon return
450 * @public
451 */
452 function findVariantLink( &$link, &$nt, $forTemplate = false ) {
453 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest, $wgUser;
454 $isredir = $wgRequest->getText( 'redirect', 'yes' );
455 $action = $wgRequest->getText( 'action' );
456 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
457 $disableLinkConversion = $wgDisableLangConversion || $wgDisableTitleConversion;
458 $linkBatch = new LinkBatch();
459
460 $ns=NS_MAIN;
461
462 if ( $disableLinkConversion || ( !$forTemplate && ( $isredir == 'no' || $action == 'edit'
463 || $action == 'submit' || $linkconvert == 'no' || $wgUser->getOption('noconvertlink') == 1 ) ) ) {
464 return;
465 }
466
467 if(is_object($nt))
468 $ns = $nt->getNamespace();
469
470 $variants = $this->autoConvertToAllVariants($link);
471 if($variants == false) //give up
472 return;
473
474 $titles = array();
475
476 foreach( $variants as $v ) {
477 if($v != $link){
478 $varnt = Title::newFromText( $v, $ns );
479 if(!is_null($varnt)){
480 $linkBatch->addObj($varnt);
481 $titles[]=$varnt;
482 }
483 }
484 }
485
486 // fetch all variants in single query
487 $linkBatch->execute();
488
489 foreach( $titles as $varnt ) {
490 if( $varnt->getArticleID() > 0 ) {
491 $nt = $varnt;
492 $link = $v;
493 break;
494 }
495 }
496 }
497
498 /**
499 * returns language specific hash options
500 *
501 * @public
502 */
503 function getExtraHashOptions() {
504 $variant = $this->getPreferredVariant();
505 return '!' . $variant ;
506 }
507
508 /**
509 * get title text as defined in the body of the article text
510 *
511 * @public
512 */
513 function getParsedTitle() {
514 return $this->mTitleDisplay;
515 }
516
517 /**
518 * a write lock to the cache
519 *
520 * @private
521 */
522 function lockCache() {
523 global $wgMemc;
524 $success = false;
525 for($i=0; $i<30; $i++) {
526 if($success = $wgMemc->add($this->mCacheKey . "lock", 1, 10))
527 break;
528 sleep(1);
529 }
530 return $success;
531 }
532
533 /**
534 * unlock cache
535 *
536 * @private
537 */
538 function unlockCache() {
539 global $wgMemc;
540 $wgMemc->delete($this->mCacheKey . "lock");
541 }
542
543
544 /**
545 * Load default conversion tables
546 * This method must be implemented in derived class
547 *
548 * @private
549 */
550 function loadDefaultTables() {
551 $name = get_class($this);
552 wfDie("Must implement loadDefaultTables() method in class $name");
553 }
554
555 /**
556 * load conversion tables either from the cache or the disk
557 * @private
558 */
559 function loadTables($fromcache=true) {
560 global $wgMemc;
561 if( $this->mTablesLoaded )
562 return;
563 wfProfileIn( __METHOD__ );
564 $this->mTablesLoaded = true;
565 $this->mTables = false;
566 if($fromcache) {
567 wfProfileIn( __METHOD__.'-cache' );
568 $this->mTables = $wgMemc->get( $this->mCacheKey );
569 wfProfileOut( __METHOD__.'-cache' );
570 }
571 if ( !$this->mTables || !isset( $this->mTables[self::CACHE_VERSION_KEY] ) ) {
572 wfProfileIn( __METHOD__.'-recache' );
573 // not in cache, or we need a fresh reload.
574 // we will first load the default tables
575 // then update them using things in MediaWiki:Zhconversiontable/*
576 $this->loadDefaultTables();
577 foreach($this->mVariants as $var) {
578 $cached = $this->parseCachedTable($var);
579 $this->mTables[$var]->mergeArray($cached);
580 }
581
582 $this->postLoadTables();
583 $this->mTables[self::CACHE_VERSION_KEY] = true;
584
585 if($this->lockCache()) {
586 $wgMemc->set($this->mCacheKey, $this->mTables, 43200);
587 $this->unlockCache();
588 }
589 wfProfileOut( __METHOD__.'-recache' );
590 }
591 wfProfileOut( __METHOD__ );
592 }
593
594 /**
595 * Hook for post processig after conversion tables are loaded
596 *
597 */
598 function postLoadTables() {}
599
600 /**
601 * Reload the conversion tables
602 *
603 * @private
604 */
605 function reloadTables() {
606 if($this->mTables)
607 unset($this->mTables);
608 $this->mTablesLoaded = false;
609 $this->loadTables(false);
610 }
611
612
613 /**
614 * parse the conversion table stored in the cache
615 *
616 * the tables should be in blocks of the following form:
617 * -{
618 * word => word ;
619 * word => word ;
620 * ...
621 * }-
622 *
623 * to make the tables more manageable, subpages are allowed
624 * and will be parsed recursively if $recursive=true
625 *
626 */
627 function parseCachedTable($code, $subpage='', $recursive=true) {
628 global $wgMessageCache;
629 static $parsed = array();
630
631 if(!is_object($wgMessageCache))
632 return array();
633
634 $key = 'Conversiontable/'.$code;
635 if($subpage)
636 $key .= '/' . $subpage;
637
638 if(array_key_exists($key, $parsed))
639 return array();
640
641 if ( strpos( $code, '/' ) === false ) {
642 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
643 } else {
644 $title = Title::makeTitleSafe( NS_MEDIAWIKI, "Conversiontable/$code" );
645 if ( $title && $title->exists() ) {
646 $article = new Article( $title );
647 $txt = $article->getContents();
648 } else {
649 $txt = '';
650 }
651 }
652
653 // get all subpage links of the form
654 // [[MediaWiki:conversiontable/zh-xx/...|...]]
655 $linkhead = $this->mLangObj->getNsText(NS_MEDIAWIKI) . ':Conversiontable';
656 $subs = explode('[[', $txt);
657 $sublinks = array();
658 foreach( $subs as $sub ) {
659 $link = explode(']]', $sub, 2);
660 if(count($link) != 2)
661 continue;
662 $b = explode('|', $link[0]);
663 $b = explode('/', trim($b[0]), 3);
664 if(count($b)==3)
665 $sublink = $b[2];
666 else
667 $sublink = '';
668
669 if($b[0] == $linkhead && $b[1] == $code) {
670 $sublinks[] = $sublink;
671 }
672 }
673
674
675 // parse the mappings in this page
676 $blocks = explode($this->mMarkup['begin'], $txt);
677 array_shift($blocks);
678 $ret = array();
679 foreach($blocks as $block) {
680 $mappings = explode($this->mMarkup['end'], $block, 2);
681 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
682 $table = explode( ';', $stripped );
683 foreach( $table as $t ) {
684 $m = explode( '=>', $t );
685 if( count( $m ) != 2)
686 continue;
687 // trim any trailling comments starting with '//'
688 $tt = explode('//', $m[1], 2);
689 $ret[trim($m[0])] = trim($tt[0]);
690 }
691 }
692 $parsed[$key] = true;
693
694
695 // recursively parse the subpages
696 if($recursive) {
697 foreach($sublinks as $link) {
698 $s = $this->parseCachedTable($code, $link, $recursive);
699 $ret = array_merge($ret, $s);
700 }
701 }
702
703 if ($this->mUcfirst) {
704 foreach ($ret as $k => $v) {
705 $ret[Language::ucfirst($k)] = Language::ucfirst($v);
706 }
707 }
708 return $ret;
709 }
710
711 /**
712 * Enclose a string with the "no conversion" tag. This is used by
713 * various functions in the Parser
714 *
715 * @param string $text text to be tagged for no conversion
716 * @return string the tagged text
717 * @public
718 */
719 function markNoConversion($text, $noParse=false) {
720 # don't mark if already marked
721 if(strpos($text, $this->mMarkup['begin']) ||
722 strpos($text, $this->mMarkup['end']))
723 return $text;
724
725 $ret = $this->mMarkup['begin'] .'R|'. $text . $this->mMarkup['end'];
726 return $ret;
727 }
728
729 /**
730 * convert the sorting key for category links. this should make different
731 * keys that are variants of each other map to the same key
732 */
733 function convertCategoryKey( $key ) {
734 return $key;
735 }
736 /**
737 * hook to refresh the cache of conversion tables when
738 * MediaWiki:conversiontable* is updated
739 * @private
740 */
741 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section, $flags, $revision) {
742 $titleobj = $article->getTitle();
743 if($titleobj->getNamespace() == NS_MEDIAWIKI) {
744 $title = $titleobj->getDBkey();
745 $t = explode('/', $title, 3);
746 $c = count($t);
747 if( $c > 1 && $t[0] == 'Conversiontable' ) {
748 if(in_array($t[1], $this->mVariants)) {
749 $this->reloadTables();
750 }
751 }
752 }
753 return true;
754 }
755
756 /**
757 * Armour rendered math against conversion
758 * Wrap math into rawoutput -{R| math }- syntax
759 * @public
760 */
761 function armourMath($text){
762 $ret = $this->mMarkup['begin'] . 'R|' . $text . $this->mMarkup['end'];
763 return $ret;
764 }
765 }
766
767 /**
768 * parser for rules of language conversion , parse rules in -{ }- tag
769 * @ingroup Language
770 * @author fdcn <fdcn64@gmail.com>
771 */
772 class ConverterRule {
773 var $mText; // original text in -{text}-
774 var $mConverter; // LanguageConverter object
775 var $mManualCodeError='<strong class="error">code error!</strong>';
776 var $mRuleDisplay = '',$mRuleTitle=false;
777 var $mRules = '';// string : the text of the rules
778 var $mRulesAction = 'none';
779 var $mFlags = array();
780 var $mConvTable = array();
781 var $mBidtable = array();// array of the translation in each variant
782 var $mUnidtable = array();// array of the translation in each variant
783
784 /**
785 * Constructor
786 *
787 * @param string $text the text between -{ and }-
788 * @param object $converter a LanguageConverter object
789 * @access public
790 */
791 function __construct($text,$converter){
792 $this->mText = $text;
793 $this->mConverter=$converter;
794 foreach($converter->mVariants as $v){
795 $this->mConvTable[$v]=array();
796 }
797 }
798
799 /**
800 * check if variants array in convert array
801 *
802 * @param string $variant Variant language code
803 * @return string Translated text
804 * @public
805 */
806 function getTextInBidtable($variants){
807 if(is_string($variants)){ $variants=array($variants); }
808 if(!is_array($variants)) return false;
809 foreach ($variants as $variant){
810 if(array_key_exists($variant, $this->mBidtable)){
811 return $this->mBidtable[$variant];
812 }
813 }
814 return false;
815 }
816
817 /**
818 * Parse flags with syntax -{FLAG| ... }-
819 * @private
820 */
821 function parseFlags(){
822 $text = $this->mText;
823 if(strlen($text) < 2 ) {
824 $this->mFlags = array( 'R' );
825 $this->mRules = $text;
826 return;
827 }
828
829 $flags = array();
830 $markup = $this->mConverter->mMarkup;
831 $validFlags = $this->mConverter->mFlags;
832
833 $tt = explode($markup['flagsep'], $text, 2);
834 if(count($tt) == 2) {
835 $f = explode($markup['varsep'], $tt[0]);
836 foreach($f as $ff) {
837 $ff = trim($ff);
838 if(array_key_exists($ff, $validFlags) &&
839 !in_array($validFlags[$ff], $flags))
840 $flags[] = $validFlags[$ff];
841 }
842 $rules = $tt[1];
843 } else {
844 $rules = $text;
845 }
846
847 //check flags
848 if( in_array('R',$flags) ){
849 $flags = array('R');// remove other flags
850 } elseif ( in_array('N',$flags) ){
851 $flags = array('N');// remove other flags
852 } elseif ( in_array('-',$flags) ){
853 $flags = array('-');// remove other flags
854 } elseif (count($flags)==1 && $flags[0]=='T'){
855 $flags[]='H';
856 } elseif ( in_array('H',$flags) ){
857 // replace A flag, and remove other flags except T
858 $temp=array('+','H');
859 if(in_array('T',$flags)) $temp[] = 'T';
860 if(in_array('D',$flags)) $temp[] = 'D';
861 $flags = $temp;
862 } else {
863 if ( in_array('A',$flags)) {
864 $flags[]='+';
865 $flags[]='S';
866 }
867 if ( in_array('D',$flags) )
868 $flags=array_diff($flags,array('S'));
869 }
870 if ( count($flags)==0 )
871 $flags = array('S');
872 $this->mRules=$rules;
873 $this->mFlags=$flags;
874 }
875
876 /**
877 * generate conversion table
878 * @private
879 */
880 function parseRules() {
881 $rules = $this->mRules;
882 $flags = $this->mFlags;
883 $bidtable = array();
884 $unidtable = array();
885 $markup = $this->mConverter->mMarkup;
886
887 $choice = explode($markup['varsep'], $rules );
888 foreach($choice as $c) {
889 $v = explode($markup['codesep'], $c);
890 if(count($v) != 2)
891 continue;// syntax error, skip
892 $to=trim($v[1]);
893 $v=trim($v[0]);
894 $u = explode($markup['unidsep'], $v);
895 if(count($u) == 1) {
896 $bidtable[$v] = $to;
897 } else if(count($u) == 2){
898 $from=trim($u[0]);$v=trim($u[1]);
899 if( array_key_exists($v,$unidtable) && !is_array($unidtable[$v]) )
900 $unidtable[$v]=array($from=>$to);
901 else
902 $unidtable[$v][$from]=$to;
903 }
904 // syntax error, pass
905 if (!array_key_exists($v,$this->mConverter->mLanguageNames)){
906 $bidtable = array();
907 $unidtable = array();
908 break;
909 }
910 }
911 $this->mBidtable = $bidtable;
912 $this->mUnidtable = $unidtable;
913 }
914
915 /**
916 * @private
917 */
918 function getRulesDesc(){
919 $codesep = $this->mConverter->mDescCodeSep;
920 $varsep = $this->mConverter->mDescVarSep;
921 $text='';
922 foreach($this->mBidtable as $k => $v)
923 $text .= $this->mConverter->mLanguageNames[$k]."$codesep$v$varsep";
924 foreach($this->mUnidtable as $k => $a)
925 foreach($a as $from=>$to)
926 $text.="$from&#8658;".$this->mConverter->mLanguageNames[$k]."$codesep$to$varsep";
927 return $text;
928 }
929
930 /**
931 * Parse rules conversion
932 * @private
933 */
934 function getRuleConvertedStr($variant,$doConvert){
935 $bidtable = $this->mBidtable;
936 $unidtable = $this->mUnidtable;
937
938 if( count($bidtable) + count($unidtable) == 0 ){
939 return $this->mRules;
940 } elseif ($doConvert){// the text converted
941 // display current variant in bidirectional array
942 $disp = $this->getTextInBidtable($variant);
943 // or display current variant in fallbacks
944 if(!$disp)
945 $disp = $this->getTextInBidtable(
946 $this->mConverter->getVariantFallbacks($variant));
947 // or display current variant in unidirectional array
948 if(!$disp && array_key_exists($variant,$unidtable)){
949 $disp = array_values($unidtable[$variant]);
950 $disp = $disp[0];
951 }
952 // or display frist text under disable manual convert
953 if(!$disp && $this->mConverter->mManualLevel[$variant]=='disable') {
954 if(count($bidtable)>0){
955 $disp = array_values($bidtable);
956 $disp = $disp[0];
957 } else {
958 $disp = array_values($unidtable);
959 $disp = array_values($disp[0]);
960 $disp = $disp[0];
961 }
962 }
963 return $disp;
964 } else {// no convert
965 return $this->mRules;
966 }
967 }
968
969 /**
970 * generate conversion table for all text
971 * @private
972 */
973 function generateConvTable(){
974 $flags = $this->mFlags;
975 $bidtable = $this->mBidtable;
976 $unidtable = $this->mUnidtable;
977 $manLevel = $this->mConverter->mManualLevel;
978
979 $vmarked=array();
980 foreach($this->mConverter->mVariants as $v) {
981 /* for bidirectional array
982 fill in the missing variants, if any,
983 with fallbacks */
984 if(!array_key_exists($v, $bidtable)) {
985 $variantFallbacks = $this->mConverter->getVariantFallbacks($v);
986 $vf = $this->getTextInBidtable($variantFallbacks);
987 if($vf) $bidtable[$v] = $vf;
988 }
989
990 if(array_key_exists($v,$bidtable)){
991 foreach($vmarked as $vo){
992 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
993 // or -{H|zh:WordZh;zh-tw:WordTw}- or -{-|zh:WordZh;zh-tw:WordTw}-
994 // to introduce a custom mapping between
995 // words WordZh and WordTw in the whole text
996 if($manLevel[$v]=='bidirectional'){
997 $this->mConvTable[$v][$bidtable[$vo]]=$bidtable[$v];
998 }
999 if($manLevel[$vo]=='bidirectional'){
1000 $this->mConvTable[$vo][$bidtable[$v]]=$bidtable[$vo];
1001 }
1002 }
1003 $vmarked[]=$v;
1004 }
1005 /*for unidirectional array
1006 fill to convert tables */
1007 $allow_unid = $manLevel[$v]=='bidirectional'
1008 || $manLevel[$v]=='unidirectional';
1009 if($allow_unid && array_key_exists($v,$unidtable)){
1010 $ct=$this->mConvTable[$v];
1011 $this->mConvTable[$v] = array_merge($ct,$unidtable[$v]);
1012 }
1013 }
1014 }
1015
1016 /**
1017 * Parse rules and flags
1018 * @public
1019 */
1020 function parse($variant){
1021 if(!$variant) $variant = $this->mConverter->getPreferredVariant();
1022
1023 $this->parseFlags();
1024 $flags = $this->mFlags;
1025
1026 if( !in_array('R',$flags) || !in_array('N',$flags) ){
1027 //FIXME: may cause trouble here...
1028 //strip &nbsp; since it interferes with the parsing, plus,
1029 //all spaces should be stripped in this tag anyway.
1030 $this->mRules = str_replace('&nbsp;', '', $this->mRules);
1031 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1032 $this->mRules = str_replace('=&gt;','=>',$this->mRules);
1033
1034 $this->parseRules();
1035 }
1036 $rules = $this->mRules;
1037
1038 if(count($this->mBidtable)==0 && count($this->mUnidtable)==0){
1039 if(in_array('+',$flags) || in_array('-',$flags))
1040 // fill all variants if text in -{A/H/-|text} without rules
1041 foreach($this->mConverter->mVariants as $v)
1042 $this->mBidtable[$v] = $rules;
1043 elseif (!in_array('N',$flags) && !in_array('T',$flags) )
1044 $this->mFlags = $flags = array('R');
1045 }
1046
1047 if( in_array('R',$flags) ) {
1048 // if we don't do content convert, still strip the -{}- tags
1049 $this->mRuleDisplay = $rules;
1050 } elseif ( in_array('N',$flags) ){
1051 // proces N flag: output current variant name
1052 $this->mRuleDisplay = $this->mConverter->mLanguageNames[trim($rules)];
1053 } elseif ( in_array('D',$flags) ){
1054 // proces D flag: output rules description
1055 $this->mRuleDisplay = $this->getRulesDesc();
1056 } elseif ( in_array('H',$flags) || in_array('-',$flags) ) {
1057 // proces H,- flag or T only: output nothing
1058 $this->mRuleDisplay = '';
1059 } elseif ( in_array('S',$flags) ){
1060 $this->mRuleDisplay = $this->getRuleConvertedStr($variant,
1061 $this->mConverter->mDoContentConvert);
1062 } else {
1063 $this->mRuleDisplay= $this->mManualCodeError;
1064 }
1065 // proces T flag
1066 if ( in_array('T',$flags) ) {
1067 $this->mRuleTitle = $this->getRuleConvertedStr($variant,
1068 $this->mConverter->mDoTitleConvert);
1069 }
1070
1071 if (in_array('-', $flags))
1072 $this->mRulesAction='remove';
1073 if (in_array('+', $flags))
1074 $this->mRulesAction='add';
1075
1076 $this->generateConvTable();
1077 }
1078
1079 /**
1080 * @public
1081 */
1082 function hasRules(){
1083 // TODO:
1084 }
1085
1086 /**
1087 * get display text on markup -{...}-
1088 * @public
1089 */
1090 function getDisplay(){
1091 return $this->mRuleDisplay;
1092 }
1093 /**
1094 * get converted title
1095 * @public
1096 */
1097 function getTitle(){
1098 return $this->mRuleTitle;
1099 }
1100
1101 /**
1102 * return how deal with conversion rules
1103 * @public
1104 */
1105 function getRulesAction(){
1106 return $this->mRulesAction;
1107 }
1108
1109 /**
1110 * get conversion table ( bidirectional and unidirectional conversion table )
1111 * @public
1112 */
1113 function getConvTable(){
1114 return $this->mConvTable;
1115 }
1116
1117 /**
1118 * get conversion rules string
1119 * @public
1120 */
1121 function getRules(){
1122 return $this->mRules;
1123 }
1124
1125 /**
1126 * get conversion flags
1127 * @public
1128 */
1129 function getFlags(){
1130 return $this->mFlags;
1131 }
1132 }