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