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