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