Add some logging for weird redirected POSTs
[lhc/web/wiklou.git] / languages / LanguageConverter.php
1 <?php
2 /**
3 * Contains the LanguageConverter class and ConverterRule class
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Language
22 */
23
24 /**
25 * Base class for language conversion.
26 * @ingroup Language
27 *
28 * @author Zhengzhu Feng <zhengzhu@gmail.com>
29 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>, PhiLiP <philip.npc@gmail.com>
30 */
31 class LanguageConverter {
32
33 /**
34 * languages supporting variants
35 * @since 1.20
36 * @var array
37 */
38 static public $languagesWithVariants = array(
39 'gan',
40 'iu',
41 'kk',
42 'ku',
43 'shi',
44 'sr',
45 'tg',
46 'uz',
47 'zh',
48 );
49
50 public $mMainLanguageCode;
51 public $mVariants, $mVariantFallbacks, $mVariantNames;
52 public $mTablesLoaded = false;
53 public $mTables;
54 // 'bidirectional' 'unidirectional' 'disable' for each variant
55 public $mManualLevel;
56
57 /**
58 * @var String: memcached key name
59 */
60 public $mCacheKey;
61
62 public $mLangObj;
63 public $mFlags;
64 public $mDescCodeSep = ':', $mDescVarSep = ';';
65 public $mUcfirst = false;
66 public $mConvRuleTitle = false;
67 public $mURLVariant;
68 public $mUserVariant;
69 public $mHeaderVariant;
70 public $mMaxDepth = 10;
71 public $mVarSeparatorPattern;
72
73 const CACHE_VERSION_KEY = 'VERSION 6';
74
75 /**
76 * Constructor
77 *
78 * @param $langobj Language: the Language Object
79 * @param $maincode String: the main language code of this language
80 * @param $variants Array: the supported variants of this language
81 * @param $variantfallbacks Array: the fallback language of each variant
82 * @param $flags Array: defining the custom strings that maps to the flags
83 * @param $manualLevel Array: limit for supported variants
84 */
85 public function __construct( $langobj, $maincode, $variants = array(),
86 $variantfallbacks = array(), $flags = array(),
87 $manualLevel = array() ) {
88 global $wgDisabledVariants;
89 $this->mLangObj = $langobj;
90 $this->mMainLanguageCode = $maincode;
91 $this->mVariants = array_diff( $variants, $wgDisabledVariants );
92 $this->mVariantFallbacks = $variantfallbacks;
93 $this->mVariantNames = Language::fetchLanguageNames();
94 $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
95 $defaultflags = array(
96 // 'S' show converted text
97 // '+' add rules for alltext
98 // 'E' the gave flags is error
99 // these flags above are reserved for program
100 'A' => 'A', // add rule for convert code (all text convert)
101 'T' => 'T', // title convert
102 'R' => 'R', // raw content
103 'D' => 'D', // convert description (subclass implement)
104 '-' => '-', // remove convert (not implement)
105 'H' => 'H', // add rule for convert code
106 // (but no display in placed code)
107 'N' => 'N' // current variant name
108 );
109 $this->mFlags = array_merge( $defaultflags, $flags );
110 foreach ( $this->mVariants as $v ) {
111 if ( array_key_exists( $v, $manualLevel ) ) {
112 $this->mManualLevel[$v] = $manualLevel[$v];
113 } else {
114 $this->mManualLevel[$v] = 'bidirectional';
115 }
116 $this->mFlags[$v] = $v;
117 }
118 }
119
120 /**
121 * Get all valid variants.
122 * Call this instead of using $this->mVariants directly.
123 *
124 * @return Array: contains all valid variants
125 */
126 public function getVariants() {
127 return $this->mVariants;
128 }
129
130 /**
131 * In case some variant is not defined in the markup, we need
132 * to have some fallback. For example, in zh, normally people
133 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
134 * when zh-sg is preferred but not defined, we will pick zh-hans
135 * in this case. Right now this is only used by zh.
136 *
137 * @param $variant String: the language code of the variant
138 * @return String|array: The code of the fallback language or the
139 * main code if there is no fallback
140 */
141 public function getVariantFallbacks( $variant ) {
142 if ( isset( $this->mVariantFallbacks[$variant] ) ) {
143 return $this->mVariantFallbacks[$variant];
144 }
145 return $this->mMainLanguageCode;
146 }
147
148 /**
149 * Get the title produced by the conversion rule.
150 * @return String: The converted title text
151 */
152 public function getConvRuleTitle() {
153 return $this->mConvRuleTitle;
154 }
155
156 /**
157 * Get preferred language variant.
158 * @return String: the preferred language code
159 */
160 public function getPreferredVariant() {
161 global $wgDefaultLanguageVariant, $wgUser;
162
163 $req = $this->getURLVariant();
164
165 if ( $wgUser->isLoggedIn() && !$req ) {
166 $req = $this->getUserVariant();
167 } elseif ( !$req ) {
168 $req = $this->getHeaderVariant();
169 }
170
171 if ( $wgDefaultLanguageVariant && !$req ) {
172 $req = $this->validateVariant( $wgDefaultLanguageVariant );
173 }
174
175 // This function, unlike the other get*Variant functions, is
176 // not memoized (i.e. there return value is not cached) since
177 // new information might appear during processing after this
178 // is first called.
179 if ( $this->validateVariant( $req ) ) {
180 return $req;
181 }
182 return $this->mMainLanguageCode;
183 }
184
185 /**
186 * Get default variant.
187 * This function would not be affected by user's settings
188 * @return String: the default variant code
189 */
190 public function getDefaultVariant() {
191 global $wgDefaultLanguageVariant;
192
193 $req = $this->getURLVariant();
194
195 if ( !$req ) {
196 $req = $this->getHeaderVariant();
197 }
198
199 if ( $wgDefaultLanguageVariant && !$req ) {
200 $req = $this->validateVariant( $wgDefaultLanguageVariant );
201 }
202
203 if ( $req ) {
204 return $req;
205 }
206 return $this->mMainLanguageCode;
207 }
208
209 /**
210 * Validate the variant
211 * @param $variant String: the variant to validate
212 * @return Mixed: returns the variant if it is valid, null otherwise
213 */
214 public function validateVariant( $variant = null ) {
215 if ( $variant !== null && in_array( $variant, $this->mVariants ) ) {
216 return $variant;
217 }
218 return null;
219 }
220
221 /**
222 * Get the variant specified in the URL
223 *
224 * @return Mixed: variant if one found, false otherwise.
225 */
226 public function getURLVariant() {
227 global $wgRequest;
228
229 if ( $this->mURLVariant ) {
230 return $this->mURLVariant;
231 }
232
233 // see if the preference is set in the request
234 $ret = $wgRequest->getText( 'variant' );
235
236 if ( !$ret ) {
237 $ret = $wgRequest->getVal( 'uselang' );
238 }
239
240 return $this->mURLVariant = $this->validateVariant( $ret );
241 }
242
243 /**
244 * Determine if the user has a variant set.
245 *
246 * @return Mixed: variant if one found, false otherwise.
247 */
248 protected function getUserVariant() {
249 global $wgUser, $wgContLang;
250
251 // memoizing this function wreaks havoc on parserTest.php
252 /*
253 if ( $this->mUserVariant ) {
254 return $this->mUserVariant;
255 }
256 */
257
258 // Get language variant preference from logged in users
259 // Don't call this on stub objects because that causes infinite
260 // recursion during initialisation
261 if ( $wgUser->isLoggedIn() ) {
262 if ( $this->mMainLanguageCode == $wgContLang->getCode() ) {
263 $ret = $wgUser->getOption( 'variant' );
264 } else {
265 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode );
266 }
267 } else {
268 // figure out user lang without constructing wgLang to avoid
269 // infinite recursion
270 $ret = $wgUser->getOption( 'language' );
271 }
272
273 return $this->mUserVariant = $this->validateVariant( $ret );
274 }
275
276 /**
277 * Determine the language variant from the Accept-Language header.
278 *
279 * @return Mixed: variant if one found, false otherwise.
280 */
281 protected function getHeaderVariant() {
282 global $wgRequest;
283
284 if ( $this->mHeaderVariant ) {
285 return $this->mHeaderVariant;
286 }
287
288 // see if some supported language variant is set in the
289 // HTTP header.
290 $languages = array_keys( $wgRequest->getAcceptLang() );
291 if ( empty( $languages ) ) {
292 return null;
293 }
294
295 $fallbackLanguages = array();
296 foreach ( $languages as $language ) {
297 $this->mHeaderVariant = $this->validateVariant( $language );
298 if ( $this->mHeaderVariant ) {
299 break;
300 }
301
302 // To see if there are fallbacks of current language.
303 // We record these fallback variants, and process
304 // them later.
305 $fallbacks = $this->getVariantFallbacks( $language );
306 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode ) {
307 $fallbackLanguages[] = $fallbacks;
308 } elseif ( is_array( $fallbacks ) ) {
309 $fallbackLanguages =
310 array_merge( $fallbackLanguages, $fallbacks );
311 }
312 }
313
314 if ( !$this->mHeaderVariant ) {
315 // process fallback languages now
316 $fallback_languages = array_unique( $fallbackLanguages );
317 foreach ( $fallback_languages as $language ) {
318 $this->mHeaderVariant = $this->validateVariant( $language );
319 if ( $this->mHeaderVariant ) {
320 break;
321 }
322 }
323 }
324
325 return $this->mHeaderVariant;
326 }
327
328 /**
329 * Dictionary-based conversion.
330 * This function would not parse the conversion rules.
331 * If you want to parse rules, try to use convert() or
332 * convertTo().
333 *
334 * @param $text String the text to be converted
335 * @param $toVariant bool|string the target language code
336 * @return String the converted text
337 */
338 public function autoConvert( $text, $toVariant = false ) {
339 wfProfileIn( __METHOD__ );
340
341 $this->loadTables();
342
343 if ( !$toVariant ) {
344 $toVariant = $this->getPreferredVariant();
345 if ( !$toVariant ) {
346 wfProfileOut( __METHOD__ );
347 return $text;
348 }
349 }
350
351 if ( $this->guessVariant( $text, $toVariant ) ) {
352 wfProfileOut( __METHOD__ );
353 return $text;
354 }
355
356 /* we convert everything except:
357 1. HTML markups (anything between < and >)
358 2. HTML entities
359 3. placeholders created by the parser
360 */
361 global $wgParser;
362 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
363 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
364 } else {
365 $marker = '';
366 }
367
368 // this one is needed when the text is inside an HTML markup
369 $htmlfix = '|<[^>]+$|^[^<>]*>';
370
371 // disable convert to variants between <code> tags
372 $codefix = '<code>.+?<\/code>|';
373 // disable conversion of <script> tags
374 $scriptfix = '<script.*?>.*?<\/script>|';
375 // disable conversion of <pre> tags
376 $prefix = '<pre.*?>.*?<\/pre>|';
377
378 $reg = '/' . $codefix . $scriptfix . $prefix .
379 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
380 $startPos = 0;
381 $sourceBlob = '';
382 $literalBlob = '';
383
384 // Guard against delimiter nulls in the input
385 $text = str_replace( "\000", '', $text );
386
387 $markupMatches = null;
388 $elementMatches = null;
389 while ( $startPos < strlen( $text ) ) {
390 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
391 $elementPos = $markupMatches[0][1];
392 $element = $markupMatches[0][0];
393 } else {
394 $elementPos = strlen( $text );
395 $element = '';
396 }
397
398 // Queue the part before the markup for translation in a batch
399 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
400
401 // Advance to the next position
402 $startPos = $elementPos + strlen( $element );
403
404 // Translate any alt or title attributes inside the matched element
405 if ( $element !== '' && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element,
406 $elementMatches ) )
407 {
408 $attrs = Sanitizer::decodeTagAttributes( $elementMatches[2] );
409 $changed = false;
410 foreach ( array( 'title', 'alt' ) as $attrName ) {
411 if ( !isset( $attrs[$attrName] ) ) {
412 continue;
413 }
414 $attr = $attrs[$attrName];
415 // Don't convert URLs
416 if ( !strpos( $attr, '://' ) ) {
417 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
418 }
419
420 // Remove HTML tags to avoid disrupting the layout
421 $attr = preg_replace( '/<[^>]+>/', '', $attr );
422 if ( $attr !== $attrs[$attrName] ) {
423 $attrs[$attrName] = $attr;
424 $changed = true;
425 }
426 }
427 if ( $changed ) {
428 $element = $elementMatches[1] . Html::expandAttributes( $attrs ) .
429 $elementMatches[3];
430 }
431 }
432 $literalBlob .= $element . "\000";
433 }
434
435 // Do the main translation batch
436 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
437
438 // Put the output back together
439 $translatedIter = StringUtils::explode( "\000", $translatedBlob );
440 $literalIter = StringUtils::explode( "\000", $literalBlob );
441 $output = '';
442 while ( $translatedIter->valid() && $literalIter->valid() ) {
443 $output .= $translatedIter->current();
444 $output .= $literalIter->current();
445 $translatedIter->next();
446 $literalIter->next();
447 }
448
449 wfProfileOut( __METHOD__ );
450 return $output;
451 }
452
453 /**
454 * Translate a string to a variant.
455 * Doesn't parse rules or do any of that other stuff, for that use
456 * convert() or convertTo().
457 *
458 * @param $text String: text to convert
459 * @param $variant String: variant language code
460 * @return String: translated text
461 */
462 public function translate( $text, $variant ) {
463 wfProfileIn( __METHOD__ );
464 // If $text is empty or only includes spaces, do nothing
465 // Otherwise translate it
466 if ( trim( $text ) ) {
467 $this->loadTables();
468 $text = $this->mTables[$variant]->replace( $text );
469 }
470 wfProfileOut( __METHOD__ );
471 return $text;
472 }
473
474 /**
475 * Call translate() to convert text to all valid variants.
476 *
477 * @param $text String: the text to be converted
478 * @return Array: variant => converted text
479 */
480 public function autoConvertToAllVariants( $text ) {
481 wfProfileIn( __METHOD__ );
482 $this->loadTables();
483
484 $ret = array();
485 foreach ( $this->mVariants as $variant ) {
486 $ret[$variant] = $this->translate( $text, $variant );
487 }
488
489 wfProfileOut( __METHOD__ );
490 return $ret;
491 }
492
493 /**
494 * Convert link text to all valid variants.
495 * In the first, this function only convert text outside the
496 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
497 * titles, the text will get all converted always.
498 * So I removed this feature and deprecated the function.
499 *
500 * @param $text String: the text to be converted
501 * @return Array: variant => converted text
502 * @deprecated since 1.17 Use autoConvertToAllVariants() instead
503 */
504 public function convertLinkToAllVariants( $text ) {
505 return $this->autoConvertToAllVariants( $text );
506 }
507
508 /**
509 * Apply manual conversion rules.
510 *
511 * @param $convRule ConverterRule Object of ConverterRule
512 */
513 protected function applyManualConv( $convRule ) {
514 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
515 // title conversion.
516 // Bug 24072: $mConvRuleTitle was overwritten by other manual
517 // rule(s) not for title, this breaks the title conversion.
518 $newConvRuleTitle = $convRule->getTitle();
519 if ( $newConvRuleTitle ) {
520 // So I add an empty check for getTitle()
521 $this->mConvRuleTitle = $newConvRuleTitle;
522 }
523
524 // merge/remove manual conversion rules to/from global table
525 $convTable = $convRule->getConvTable();
526 $action = $convRule->getRulesAction();
527 foreach ( $convTable as $variant => $pair ) {
528 if ( !$this->validateVariant( $variant ) ) {
529 continue;
530 }
531
532 if ( $action == 'add' ) {
533 foreach ( $pair as $from => $to ) {
534 // to ensure that $from and $to not be left blank
535 // so $this->translate() could always return a string
536 if ( $from || $to ) {
537 // more efficient than array_merge(), about 2.5 times.
538 $this->mTables[$variant]->setPair( $from, $to );
539 }
540 }
541 } elseif ( $action == 'remove' ) {
542 $this->mTables[$variant]->removeArray( $pair );
543 }
544 }
545 }
546
547 /**
548 * Auto convert a Title object to a readable string in the
549 * preferred variant.
550 *
551 * @param $title Title a object of Title
552 * @return String: converted title text
553 */
554 public function convertTitle( $title ) {
555 $variant = $this->getPreferredVariant();
556 $index = $title->getNamespace();
557 if ( $index !== NS_MAIN ) {
558 $text = $this->convertNamespace( $index ) . ':';
559 } else {
560 $text = '';
561 }
562 $text .= $this->translate( $title->getText(), $variant );
563 return $text;
564 }
565
566 /**
567 * Get the namespace display name in the preferred variant.
568 *
569 * @param $index int namespace id
570 * @return String: namespace name for display
571 */
572 public function convertNamespace( $index ) {
573 $variant = $this->getPreferredVariant();
574 if ( $index === NS_MAIN ) {
575 return '';
576 } else {
577 // First check if a message gives a converted name in the target variant.
578 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
579 if ( $nsConvMsg->exists() ) {
580 return $nsConvMsg->plain();
581 }
582 // Then check if a message gives a converted name in content language
583 // which needs extra translation to the target variant.
584 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
585 if ( $nsConvMsg->exists() ) {
586 return $this->translate( $nsConvMsg->plain(), $variant );
587 }
588 // No message exists, retrieve it from the target variant's namespace names.
589 $langObj = $this->mLangObj->factory( $variant );
590 return $langObj->getFormattedNsText( $index );
591 }
592 }
593
594 /**
595 * Convert text to different variants of a language. The automatic
596 * conversion is done in autoConvert(). Here we parse the text
597 * marked with -{}-, which specifies special conversions of the
598 * text that can not be accomplished in autoConvert().
599 *
600 * Syntax of the markup:
601 * -{code1:text1;code2:text2;...}- or
602 * -{flags|code1:text1;code2:text2;...}- or
603 * -{text}- in which case no conversion should take place for text
604 *
605 * @param $text String: text to be converted
606 * @return String: converted text
607 */
608 public function convert( $text ) {
609 $variant = $this->getPreferredVariant();
610 return $this->convertTo( $text, $variant );
611 }
612
613 /**
614 * Same as convert() except a extra parameter to custom variant.
615 *
616 * @param $text String: text to be converted
617 * @param $variant String: the target variant code
618 * @return String: converted text
619 */
620 public function convertTo( $text, $variant ) {
621 global $wgDisableLangConversion;
622 if ( $wgDisableLangConversion ) {
623 return $text;
624 }
625 // Reset converter state for a new converter run.
626 $this->mConvRuleTitle = false;
627 return $this->recursiveConvertTopLevel( $text, $variant );
628 }
629
630 /**
631 * Recursively convert text on the outside. Allow to use nested
632 * markups to custom rules.
633 *
634 * @param $text String: text to be converted
635 * @param $variant String: the target variant code
636 * @param $depth Integer: depth of recursion
637 * @return String: converted text
638 */
639 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
640 $startPos = 0;
641 $out = '';
642 $length = strlen( $text );
643 $shouldConvert = !$this->guessVariant( $text, $variant );
644
645 while ( $startPos < $length ) {
646 $pos = strpos( $text, '-{', $startPos );
647
648 if ( $pos === false ) {
649 // No more markup, append final segment
650 $fragment = substr( $text, $startPos );
651 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
652 return $out;
653 }
654
655 // Markup found
656 // Append initial segment
657 $fragment = substr( $text, $startPos, $pos - $startPos );
658 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
659
660 // Advance position
661 $startPos = $pos;
662
663 // Do recursive conversion
664 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
665 }
666
667 return $out;
668 }
669
670 /**
671 * Recursively convert text on the inside.
672 *
673 * @param $text String: text to be converted
674 * @param $variant String: the target variant code
675 * @param $startPos int
676 * @param $depth Integer: depth of recursion
677 *
678 * @throws MWException
679 * @return String: converted text
680 */
681 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
682 // Quick sanity check (no function calls)
683 if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
684 throw new MWException( __METHOD__ . ': invalid input string' );
685 }
686
687 $startPos += 2;
688 $inner = '';
689 $warningDone = false;
690 $length = strlen( $text );
691
692 while ( $startPos < $length ) {
693 $m = false;
694 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
695 if ( !$m ) {
696 // Unclosed rule
697 break;
698 }
699
700 $token = $m[0][0];
701 $pos = $m[0][1];
702
703 // Markup found
704 // Append initial segment
705 $inner .= substr( $text, $startPos, $pos - $startPos );
706
707 // Advance position
708 $startPos = $pos;
709
710 switch ( $token ) {
711 case '-{':
712 // Check max depth
713 if ( $depth >= $this->mMaxDepth ) {
714 $inner .= '-{';
715 if ( !$warningDone ) {
716 $inner .= '<span class="error">' .
717 wfMessage( 'language-converter-depth-warning' )
718 ->numParams( $this->mMaxDepth )->inContentLanguage()->text() .
719 '</span>';
720 $warningDone = true;
721 }
722 $startPos += 2;
723 continue;
724 }
725 // Recursively parse another rule
726 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
727 break;
728 case '}-':
729 // Apply the rule
730 $startPos += 2;
731 $rule = new ConverterRule( $inner, $this );
732 $rule->parse( $variant );
733 $this->applyManualConv( $rule );
734 return $rule->getDisplay();
735 default:
736 throw new MWException( __METHOD__ . ': invalid regex match' );
737 }
738 }
739
740 // Unclosed rule
741 if ( $startPos < $length ) {
742 $inner .= substr( $text, $startPos );
743 }
744 $startPos = $length;
745 return '-{' . $this->autoConvert( $inner, $variant );
746 }
747
748 /**
749 * If a language supports multiple variants, it is possible that
750 * non-existing link in one variant actually exists in another variant.
751 * This function tries to find it. See e.g. LanguageZh.php
752 *
753 * @param $link String: the name of the link
754 * @param $nt Mixed: the title object of the link
755 * @param $ignoreOtherCond Boolean: to disable other conditions when
756 * we need to transclude a template or update a category's link
757 * @return Null, the input parameters may be modified upon return
758 */
759 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
760 # If the article has already existed, there is no need to
761 # check it again, otherwise it may cause a fault.
762 if ( is_object( $nt ) && $nt->exists() ) {
763 return;
764 }
765
766 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
767 $wgUser;
768 $isredir = $wgRequest->getText( 'redirect', 'yes' );
769 $action = $wgRequest->getText( 'action' );
770 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
771 $disableLinkConversion = $wgDisableLangConversion
772 || $wgDisableTitleConversion;
773 $linkBatch = new LinkBatch();
774
775 $ns = NS_MAIN;
776
777 if ( $disableLinkConversion ||
778 ( !$ignoreOtherCond &&
779 ( $isredir == 'no'
780 || $action == 'edit'
781 || $action == 'submit'
782 || $linkconvert == 'no'
783 || $wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
784 return;
785 }
786
787 if ( is_object( $nt ) ) {
788 $ns = $nt->getNamespace();
789 }
790
791 $variants = $this->autoConvertToAllVariants( $link );
792 if ( !$variants ) { // give up
793 return;
794 }
795
796 $titles = array();
797
798 foreach ( $variants as $v ) {
799 if ( $v != $link ) {
800 $varnt = Title::newFromText( $v, $ns );
801 if ( !is_null( $varnt ) ) {
802 $linkBatch->addObj( $varnt );
803 $titles[] = $varnt;
804 }
805 }
806 }
807
808 // fetch all variants in single query
809 $linkBatch->execute();
810
811 foreach ( $titles as $varnt ) {
812 if ( $varnt->getArticleID() > 0 ) {
813 $nt = $varnt;
814 $link = $varnt->getText();
815 break;
816 }
817 }
818 }
819
820 /**
821 * Returns language specific hash options.
822 *
823 * @return string
824 */
825 public function getExtraHashOptions() {
826 $variant = $this->getPreferredVariant();
827 return '!' . $variant;
828 }
829
830 /**
831 * Guess if a text is written in a variant. This should be implemented in subclasses.
832 *
833 * @param string $text the text to be checked
834 * @param string $variant language code of the variant to be checked for
835 * @return bool true if $text appears to be written in $variant, false if not
836 *
837 * @author Nikola Smolenski <smolensk@eunet.rs>
838 * @since 1.19
839 */
840 public function guessVariant( $text, $variant ) {
841 return false;
842 }
843
844 /**
845 * Load default conversion tables.
846 * This method must be implemented in derived class.
847 *
848 * @private
849 * @throws MWException
850 */
851 function loadDefaultTables() {
852 $name = get_class( $this );
853 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
854 }
855
856 /**
857 * Load conversion tables either from the cache or the disk.
858 * @private
859 * @param $fromCache Boolean: load from memcached? Defaults to true.
860 */
861 function loadTables( $fromCache = true ) {
862 global $wgLangConvMemc;
863
864 if ( $this->mTablesLoaded ) {
865 return;
866 }
867
868 wfProfileIn( __METHOD__ );
869 $this->mTablesLoaded = true;
870 $this->mTables = false;
871 if ( $fromCache ) {
872 wfProfileIn( __METHOD__ . '-cache' );
873 $this->mTables = $wgLangConvMemc->get( $this->mCacheKey );
874 wfProfileOut( __METHOD__ . '-cache' );
875 }
876 if ( !$this->mTables
877 || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
878 wfProfileIn( __METHOD__ . '-recache' );
879 // not in cache, or we need a fresh reload.
880 // We will first load the default tables
881 // then update them using things in MediaWiki:Conversiontable/*
882 $this->loadDefaultTables();
883 foreach ( $this->mVariants as $var ) {
884 $cached = $this->parseCachedTable( $var );
885 $this->mTables[$var]->mergeArray( $cached );
886 }
887
888 $this->postLoadTables();
889 $this->mTables[self::CACHE_VERSION_KEY] = true;
890
891 $wgLangConvMemc->set( $this->mCacheKey, $this->mTables, 43200 );
892 wfProfileOut( __METHOD__ . '-recache' );
893 }
894 wfProfileOut( __METHOD__ );
895 }
896
897 /**
898 * Hook for post processing after conversion tables are loaded.
899 */
900 function postLoadTables() { }
901
902 /**
903 * Reload the conversion tables.
904 *
905 * @private
906 */
907 function reloadTables() {
908 if ( $this->mTables ) {
909 unset( $this->mTables );
910 }
911 $this->mTablesLoaded = false;
912 $this->loadTables( false );
913 }
914
915 /**
916 * Parse the conversion table stored in the cache.
917 *
918 * The tables should be in blocks of the following form:
919 * -{
920 * word => word ;
921 * word => word ;
922 * ...
923 * }-
924 *
925 * To make the tables more manageable, subpages are allowed
926 * and will be parsed recursively if $recursive == true.
927 *
928 * @param $code String: language code
929 * @param $subpage String: subpage name
930 * @param $recursive Boolean: parse subpages recursively? Defaults to true.
931 *
932 * @return array
933 */
934 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
935 static $parsed = array();
936
937 $key = 'Conversiontable/' . $code;
938 if ( $subpage ) {
939 $key .= '/' . $subpage;
940 }
941 if ( array_key_exists( $key, $parsed ) ) {
942 return array();
943 }
944
945 $parsed[$key] = true;
946
947 if ( $subpage === '' ) {
948 $txt = MessageCache::singleton()->getMsgFromNamespace( $key, $code );
949 } else {
950 $txt = false;
951 $title = Title::makeTitleSafe( NS_MEDIAWIKI, $key );
952 if ( $title && $title->exists() ) {
953 $revision = Revision::newFromTitle( $title );
954 if ( $revision ) {
955 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT ) {
956 $txt = $revision->getContent( Revision::RAW )->getNativeData();
957 }
958
959 // @todo in the future, use a specialized content model, perhaps based on json!
960 }
961 }
962 }
963
964 # Nothing to parse if there's no text
965 if ( $txt === false || $txt === null || $txt === '' ) {
966 return array();
967 }
968
969 // get all subpage links of the form
970 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
971 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
972 ':Conversiontable';
973 $subs = StringUtils::explode( '[[', $txt );
974 $sublinks = array();
975 foreach ( $subs as $sub ) {
976 $link = explode( ']]', $sub, 2 );
977 if ( count( $link ) != 2 ) {
978 continue;
979 }
980 $b = explode( '|', $link[0], 2 );
981 $b = explode( '/', trim( $b[0] ), 3 );
982 if ( count( $b ) == 3 ) {
983 $sublink = $b[2];
984 } else {
985 $sublink = '';
986 }
987
988 if ( $b[0] == $linkhead && $b[1] == $code ) {
989 $sublinks[] = $sublink;
990 }
991 }
992
993 // parse the mappings in this page
994 $blocks = StringUtils::explode( '-{', $txt );
995 $ret = array();
996 $first = true;
997 foreach ( $blocks as $block ) {
998 if ( $first ) {
999 // Skip the part before the first -{
1000 $first = false;
1001 continue;
1002 }
1003 $mappings = explode( '}-', $block, 2 );
1004 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
1005 $mappings[0] );
1006 $table = StringUtils::explode( ';', $stripped );
1007 foreach ( $table as $t ) {
1008 $m = explode( '=>', $t, 3 );
1009 if ( count( $m ) != 2 ) {
1010 continue;
1011 }
1012 // trim any trailling comments starting with '//'
1013 $tt = explode( '//', $m[1], 2 );
1014 $ret[trim( $m[0] )] = trim( $tt[0] );
1015 }
1016 }
1017
1018 // recursively parse the subpages
1019 if ( $recursive ) {
1020 foreach ( $sublinks as $link ) {
1021 $s = $this->parseCachedTable( $code, $link, $recursive );
1022 $ret = array_merge( $ret, $s );
1023 }
1024 }
1025
1026 if ( $this->mUcfirst ) {
1027 foreach ( $ret as $k => $v ) {
1028 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
1029 }
1030 }
1031 return $ret;
1032 }
1033
1034 /**
1035 * Enclose a string with the "no conversion" tag. This is used by
1036 * various functions in the Parser.
1037 *
1038 * @param $text String: text to be tagged for no conversion
1039 * @param $noParse Boolean: unused
1040 * @return String: the tagged text
1041 */
1042 public function markNoConversion( $text, $noParse = false ) {
1043 # don't mark if already marked
1044 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
1045 return $text;
1046 }
1047
1048 $ret = "-{R|$text}-";
1049 return $ret;
1050 }
1051
1052 /**
1053 * Convert the sorting key for category links. This should make different
1054 * keys that are variants of each other map to the same key.
1055 *
1056 * @param $key string
1057 *
1058 * @return string
1059 */
1060 function convertCategoryKey( $key ) {
1061 return $key;
1062 }
1063
1064 /**
1065 * Hook to refresh the cache of conversion tables when
1066 * MediaWiki:Conversiontable* is updated.
1067 * @private
1068 *
1069 * @param $page WikiPage object
1070 * @param $user Object: User object for the current user
1071 * @param $content Content: new page content
1072 * @param $summary String: edit summary of the edit
1073 * @param $isMinor Boolean: was the edit marked as minor?
1074 * @param $isWatch Boolean: did the user watch this page or not?
1075 * @param $section
1076 * @param $flags int Bitfield
1077 * @param $revision Object: new Revision object or null
1078 * @return Boolean: true
1079 */
1080 function OnPageContentSaveComplete( $page, $user, $content, $summary, $isMinor,
1081 $isWatch, $section, $flags, $revision ) {
1082 $titleobj = $page->getTitle();
1083 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
1084 $title = $titleobj->getDBkey();
1085 $t = explode( '/', $title, 3 );
1086 $c = count( $t );
1087 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1088 if ( $this->validateVariant( $t[1] ) ) {
1089 $this->reloadTables();
1090 }
1091 }
1092 }
1093 return true;
1094 }
1095
1096 /**
1097 * Armour rendered math against conversion.
1098 * Escape special chars in parsed math text. (in most cases are img elements)
1099 *
1100 * @param $text String: text to armour against conversion
1101 * @return String: armoured text where { and } have been converted to
1102 * &#123; and &#125;
1103 */
1104 public function armourMath( $text ) {
1105 // convert '-{' and '}-' to '-&#123;' and '&#125;-' to prevent
1106 // any unwanted markup appearing in the math image tag.
1107 $text = strtr( $text, array( '-{' => '-&#123;', '}-' => '&#125;-' ) );
1108 return $text;
1109 }
1110
1111 /**
1112 * Get the cached separator pattern for ConverterRule::parseRules()
1113 */
1114 function getVarSeparatorPattern() {
1115 if ( is_null( $this->mVarSeparatorPattern ) ) {
1116 // varsep_pattern for preg_split:
1117 // text should be splited by ";" only if a valid variant
1118 // name exist after the markup, for example:
1119 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1120 // <span style="font-size:120%;">yyy</span>;}-
1121 // we should split it as:
1122 // array(
1123 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1124 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1125 // [2] => ''
1126 // )
1127 $pat = '/;\s*(?=';
1128 foreach ( $this->mVariants as $variant ) {
1129 // zh-hans:xxx;zh-hant:yyy
1130 $pat .= $variant . '\s*:|';
1131 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1132 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1133 }
1134 $pat .= '\s*$)/';
1135 $this->mVarSeparatorPattern = $pat;
1136 }
1137 return $this->mVarSeparatorPattern;
1138 }
1139 }
1140
1141 /**
1142 * Parser for rules of language conversion , parse rules in -{ }- tag.
1143 * @ingroup Language
1144 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1145 */
1146 class ConverterRule {
1147 public $mText; // original text in -{text}-
1148 public $mConverter; // LanguageConverter object
1149 public $mRuleDisplay = '';
1150 public $mRuleTitle = false;
1151 public $mRules = '';// string : the text of the rules
1152 public $mRulesAction = 'none';
1153 public $mFlags = array();
1154 public $mVariantFlags = array();
1155 public $mConvTable = array();
1156 public $mBidtable = array();// array of the translation in each variant
1157 public $mUnidtable = array();// array of the translation in each variant
1158
1159 /**
1160 * Constructor
1161 *
1162 * @param $text String: the text between -{ and }-
1163 * @param $converter LanguageConverter object
1164 */
1165 public function __construct( $text, $converter ) {
1166 $this->mText = $text;
1167 $this->mConverter = $converter;
1168 }
1169
1170 /**
1171 * Check if variants array in convert array.
1172 *
1173 * @param $variants Array or string: variant language code
1174 * @return String: translated text
1175 */
1176 public function getTextInBidtable( $variants ) {
1177 $variants = (array)$variants;
1178 if ( !$variants ) {
1179 return false;
1180 }
1181 foreach ( $variants as $variant ) {
1182 if ( isset( $this->mBidtable[$variant] ) ) {
1183 return $this->mBidtable[$variant];
1184 }
1185 }
1186 return false;
1187 }
1188
1189 /**
1190 * Parse flags with syntax -{FLAG| ... }-
1191 * @private
1192 */
1193 function parseFlags() {
1194 $text = $this->mText;
1195 $flags = array();
1196 $variantFlags = array();
1197
1198 $sepPos = strpos( $text, '|' );
1199 if ( $sepPos !== false ) {
1200 $validFlags = $this->mConverter->mFlags;
1201 $f = StringUtils::explode( ';', substr( $text, 0, $sepPos ) );
1202 foreach ( $f as $ff ) {
1203 $ff = trim( $ff );
1204 if ( isset( $validFlags[$ff] ) ) {
1205 $flags[$validFlags[$ff]] = true;
1206 }
1207 }
1208 $text = strval( substr( $text, $sepPos + 1 ) );
1209 }
1210
1211 if ( !$flags ) {
1212 $flags['S'] = true;
1213 } elseif ( isset( $flags['R'] ) ) {
1214 $flags = array( 'R' => true );// remove other flags
1215 } elseif ( isset( $flags['N'] ) ) {
1216 $flags = array( 'N' => true );// remove other flags
1217 } elseif ( isset( $flags['-'] ) ) {
1218 $flags = array( '-' => true );// remove other flags
1219 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1220 $flags['H'] = true;
1221 } elseif ( isset( $flags['H'] ) ) {
1222 // replace A flag, and remove other flags except T
1223 $temp = array( '+' => true, 'H' => true );
1224 if ( isset( $flags['T'] ) ) {
1225 $temp['T'] = true;
1226 }
1227 if ( isset( $flags['D'] ) ) {
1228 $temp['D'] = true;
1229 }
1230 $flags = $temp;
1231 } else {
1232 if ( isset( $flags['A'] ) ) {
1233 $flags['+'] = true;
1234 $flags['S'] = true;
1235 }
1236 if ( isset( $flags['D'] ) ) {
1237 unset( $flags['S'] );
1238 }
1239 // try to find flags like "zh-hans", "zh-hant"
1240 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1241 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter->mVariants );
1242 if ( $variantFlags ) {
1243 $variantFlags = array_flip( $variantFlags );
1244 $flags = array();
1245 }
1246 }
1247 $this->mVariantFlags = $variantFlags;
1248 $this->mRules = $text;
1249 $this->mFlags = $flags;
1250 }
1251
1252 /**
1253 * Generate conversion table.
1254 * @private
1255 */
1256 function parseRules() {
1257 $rules = $this->mRules;
1258 $bidtable = array();
1259 $unidtable = array();
1260 $variants = $this->mConverter->mVariants;
1261 $varsep_pattern = $this->mConverter->getVarSeparatorPattern();
1262
1263 $choice = preg_split( $varsep_pattern, $rules );
1264
1265 foreach ( $choice as $c ) {
1266 $v = explode( ':', $c, 2 );
1267 if ( count( $v ) != 2 ) {
1268 // syntax error, skip
1269 continue;
1270 }
1271 $to = trim( $v[1] );
1272 $v = trim( $v[0] );
1273 $u = explode( '=>', $v, 2 );
1274 // if $to is empty, strtr() could return a wrong result
1275 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1276 $bidtable[$v] = $to;
1277 } elseif ( count( $u ) == 2 ) {
1278 $from = trim( $u[0] );
1279 $v = trim( $u[1] );
1280 if ( array_key_exists( $v, $unidtable )
1281 && !is_array( $unidtable[$v] )
1282 && $to
1283 && in_array( $v, $variants ) ) {
1284 $unidtable[$v] = array( $from => $to );
1285 } elseif ( $to && in_array( $v, $variants ) ) {
1286 $unidtable[$v][$from] = $to;
1287 }
1288 }
1289 // syntax error, pass
1290 if ( !isset( $this->mConverter->mVariantNames[$v] ) ) {
1291 $bidtable = array();
1292 $unidtable = array();
1293 break;
1294 }
1295 }
1296 $this->mBidtable = $bidtable;
1297 $this->mUnidtable = $unidtable;
1298 }
1299
1300 /**
1301 * @private
1302 *
1303 * @return string
1304 */
1305 function getRulesDesc() {
1306 $codesep = $this->mConverter->mDescCodeSep;
1307 $varsep = $this->mConverter->mDescVarSep;
1308 $text = '';
1309 foreach ( $this->mBidtable as $k => $v ) {
1310 $text .= $this->mConverter->mVariantNames[$k] . "$codesep$v$varsep";
1311 }
1312 foreach ( $this->mUnidtable as $k => $a ) {
1313 foreach ( $a as $from => $to ) {
1314 $text .= $from . '⇒' . $this->mConverter->mVariantNames[$k] .
1315 "$codesep$to$varsep";
1316 }
1317 }
1318 return $text;
1319 }
1320
1321 /**
1322 * Parse rules conversion.
1323 * @private
1324 *
1325 * @param $variant
1326 *
1327 * @return string
1328 */
1329 function getRuleConvertedStr( $variant ) {
1330 $bidtable = $this->mBidtable;
1331 $unidtable = $this->mUnidtable;
1332
1333 if ( count( $bidtable ) + count( $unidtable ) == 0 ) {
1334 return $this->mRules;
1335 } else {
1336 // display current variant in bidirectional array
1337 $disp = $this->getTextInBidtable( $variant );
1338 // or display current variant in fallbacks
1339 if ( !$disp ) {
1340 $disp = $this->getTextInBidtable(
1341 $this->mConverter->getVariantFallbacks( $variant ) );
1342 }
1343 // or display current variant in unidirectional array
1344 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1345 $disp = array_values( $unidtable[$variant] );
1346 $disp = $disp[0];
1347 }
1348 // or display frist text under disable manual convert
1349 if ( !$disp
1350 && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
1351 if ( count( $bidtable ) > 0 ) {
1352 $disp = array_values( $bidtable );
1353 $disp = $disp[0];
1354 } else {
1355 $disp = array_values( $unidtable );
1356 $disp = array_values( $disp[0] );
1357 $disp = $disp[0];
1358 }
1359 }
1360 return $disp;
1361 }
1362 }
1363
1364 /**
1365 * Similar to getRuleConvertedStr(), but this prefers to use original
1366 * page title if $variant === $this->mConverter->mMainLanguageCode
1367 * and may return false in this case (so this title conversion rule
1368 * will be ignored and the original title is shown).
1369 *
1370 * @since 1.22
1371 * @param $variant The variant code to display page title in
1372 * @return String|false The converted title or false if just page name
1373 */
1374 function getRuleConvertedTitle( $variant ) {
1375 if ( $variant === $this->mConverter->mMainLanguageCode ) {
1376 // If a string targeting exactly this variant is set,
1377 // use it. Otherwise, just return false, so the real
1378 // page name can be shown (and because variant === main,
1379 // there'll be no further automatic conversion).
1380 $disp = $this->getTextInBidtable( $variant );
1381 if ( $disp ) {
1382 return $disp;
1383 }
1384 if ( array_key_exists( $variant, $this->mUnidtable ) ) {
1385 $disp = array_values( $this->mUnidtable[$variant] );
1386 $disp = $disp[0];
1387 }
1388 // Assigned above or still false.
1389 return $disp;
1390 } else {
1391 return $this->getRuleConvertedStr( $variant );
1392 }
1393 }
1394
1395 /**
1396 * Generate conversion table for all text.
1397 * @private
1398 */
1399 function generateConvTable() {
1400 // Special case optimisation
1401 if ( !$this->mBidtable && !$this->mUnidtable ) {
1402 $this->mConvTable = array();
1403 return;
1404 }
1405
1406 $bidtable = $this->mBidtable;
1407 $unidtable = $this->mUnidtable;
1408 $manLevel = $this->mConverter->mManualLevel;
1409
1410 $vmarked = array();
1411 foreach ( $this->mConverter->mVariants as $v ) {
1412 /* for bidirectional array
1413 fill in the missing variants, if any,
1414 with fallbacks */
1415 if ( !isset( $bidtable[$v] ) ) {
1416 $variantFallbacks =
1417 $this->mConverter->getVariantFallbacks( $v );
1418 $vf = $this->getTextInBidtable( $variantFallbacks );
1419 if ( $vf ) {
1420 $bidtable[$v] = $vf;
1421 }
1422 }
1423
1424 if ( isset( $bidtable[$v] ) ) {
1425 foreach ( $vmarked as $vo ) {
1426 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1427 // or -{H|zh:WordZh;zh-tw:WordTw}-
1428 // or -{-|zh:WordZh;zh-tw:WordTw}-
1429 // to introduce a custom mapping between
1430 // words WordZh and WordTw in the whole text
1431 if ( $manLevel[$v] == 'bidirectional' ) {
1432 $this->mConvTable[$v][$bidtable[$vo]] = $bidtable[$v];
1433 }
1434 if ( $manLevel[$vo] == 'bidirectional' ) {
1435 $this->mConvTable[$vo][$bidtable[$v]] = $bidtable[$vo];
1436 }
1437 }
1438 $vmarked[] = $v;
1439 }
1440 /* for unidirectional array fill to convert tables */
1441 if ( ( $manLevel[$v] == 'bidirectional' || $manLevel[$v] == 'unidirectional' )
1442 && isset( $unidtable[$v] ) )
1443 {
1444 if ( isset( $this->mConvTable[$v] ) ) {
1445 $this->mConvTable[$v] = array_merge( $this->mConvTable[$v], $unidtable[$v] );
1446 } else {
1447 $this->mConvTable[$v] = $unidtable[$v];
1448 }
1449 }
1450 }
1451 }
1452
1453 /**
1454 * Parse rules and flags.
1455 * @param $variant String: variant language code
1456 */
1457 public function parse( $variant = null ) {
1458 if ( !$variant ) {
1459 $variant = $this->mConverter->getPreferredVariant();
1460 }
1461
1462 $this->parseFlags();
1463 $flags = $this->mFlags;
1464
1465 // convert to specified variant
1466 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1467 if ( $this->mVariantFlags ) {
1468 // check if current variant in flags
1469 if ( isset( $this->mVariantFlags[$variant] ) ) {
1470 // then convert <text to convert> to current language
1471 $this->mRules = $this->mConverter->autoConvert( $this->mRules,
1472 $variant );
1473 } else { // if current variant no in flags,
1474 // then we check its fallback variants.
1475 $variantFallbacks =
1476 $this->mConverter->getVariantFallbacks( $variant );
1477 if ( is_array( $variantFallbacks ) ) {
1478 foreach ( $variantFallbacks as $variantFallback ) {
1479 // if current variant's fallback exist in flags
1480 if ( isset( $this->mVariantFlags[$variantFallback] ) ) {
1481 // then convert <text to convert> to fallback language
1482 $this->mRules =
1483 $this->mConverter->autoConvert( $this->mRules,
1484 $variantFallback );
1485 break;
1486 }
1487 }
1488 }
1489 }
1490 $this->mFlags = $flags = array( 'R' => true );
1491 }
1492
1493 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1494 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1495 $this->mRules = str_replace( '=&gt;', '=>', $this->mRules );
1496 $this->parseRules();
1497 }
1498 $rules = $this->mRules;
1499
1500 if ( !$this->mBidtable && !$this->mUnidtable ) {
1501 if ( isset( $flags['+'] ) || isset( $flags['-'] ) ) {
1502 // fill all variants if text in -{A/H/-|text} without rules
1503 foreach ( $this->mConverter->mVariants as $v ) {
1504 $this->mBidtable[$v] = $rules;
1505 }
1506 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1507 $this->mFlags = $flags = array( 'R' => true );
1508 }
1509 }
1510
1511 $this->mRuleDisplay = false;
1512 foreach ( $flags as $flag => $unused ) {
1513 switch ( $flag ) {
1514 case 'R':
1515 // if we don't do content convert, still strip the -{}- tags
1516 $this->mRuleDisplay = $rules;
1517 break;
1518 case 'N':
1519 // process N flag: output current variant name
1520 $ruleVar = trim( $rules );
1521 if ( isset( $this->mConverter->mVariantNames[$ruleVar] ) ) {
1522 $this->mRuleDisplay = $this->mConverter->mVariantNames[$ruleVar];
1523 } else {
1524 $this->mRuleDisplay = '';
1525 }
1526 break;
1527 case 'D':
1528 // process D flag: output rules description
1529 $this->mRuleDisplay = $this->getRulesDesc();
1530 break;
1531 case 'H':
1532 // process H,- flag or T only: output nothing
1533 $this->mRuleDisplay = '';
1534 break;
1535 case '-':
1536 $this->mRulesAction = 'remove';
1537 $this->mRuleDisplay = '';
1538 break;
1539 case '+':
1540 $this->mRulesAction = 'add';
1541 $this->mRuleDisplay = '';
1542 break;
1543 case 'S':
1544 $this->mRuleDisplay = $this->getRuleConvertedStr( $variant );
1545 break;
1546 case 'T':
1547 $this->mRuleTitle = $this->getRuleConvertedTitle( $variant );
1548 $this->mRuleDisplay = '';
1549 break;
1550 default:
1551 // ignore unknown flags (but see error case below)
1552 }
1553 }
1554 if ( $this->mRuleDisplay === false ) {
1555 $this->mRuleDisplay = '<span class="error">'
1556 . wfMessage( 'converter-manual-rule-error' )->inContentLanguage()->escaped()
1557 . '</span>';
1558 }
1559
1560 $this->generateConvTable();
1561 }
1562
1563 /**
1564 * @todo FIXME: code this function :)
1565 */
1566 public function hasRules() {
1567 // TODO:
1568 }
1569
1570 /**
1571 * Get display text on markup -{...}-
1572 * @return string
1573 */
1574 public function getDisplay() {
1575 return $this->mRuleDisplay;
1576 }
1577
1578 /**
1579 * Get converted title.
1580 * @return string
1581 */
1582 public function getTitle() {
1583 return $this->mRuleTitle;
1584 }
1585
1586 /**
1587 * Return how deal with conversion rules.
1588 * @return string
1589 */
1590 public function getRulesAction() {
1591 return $this->mRulesAction;
1592 }
1593
1594 /**
1595 * Get conversion table. (bidirectional and unidirectional
1596 * conversion table)
1597 * @return array
1598 */
1599 public function getConvTable() {
1600 return $this->mConvTable;
1601 }
1602
1603 /**
1604 * Get conversion rules string.
1605 * @return string
1606 */
1607 public function getRules() {
1608 return $this->mRules;
1609 }
1610
1611 /**
1612 * Get conversion flags.
1613 * @return array
1614 */
1615 public function getFlags() {
1616 return $this->mFlags;
1617 }
1618 }