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