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