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