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