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