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