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