Increase LanguageConverter cache version
[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
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, $variant ) . ':';
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 * @param $variant string|null variant code or null for preferred variant
571 * @return String: namespace name for display
572 */
573 public function convertNamespace( $index, $variant = null ) {
574 if ( $variant === null ) {
575 $variant = $this->getPreferredVariant();
576 }
577 if ( $index === NS_MAIN ) {
578 return '';
579 } else {
580 // First check if a message gives a converted name in the target variant.
581 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
582 if ( $nsConvMsg->exists() ) {
583 return $nsConvMsg->plain();
584 }
585 // Then check if a message gives a converted name in content language
586 // which needs extra translation to the target variant.
587 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
588 if ( $nsConvMsg->exists() ) {
589 return $this->translate( $nsConvMsg->plain(), $variant );
590 }
591 // No message exists, retrieve it from the target variant's namespace names.
592 $langObj = $this->mLangObj->factory( $variant );
593 return $langObj->getFormattedNsText( $index );
594 }
595 }
596
597 /**
598 * Convert text to different variants of a language. The automatic
599 * conversion is done in autoConvert(). Here we parse the text
600 * marked with -{}-, which specifies special conversions of the
601 * text that can not be accomplished in autoConvert().
602 *
603 * Syntax of the markup:
604 * -{code1:text1;code2:text2;...}- or
605 * -{flags|code1:text1;code2:text2;...}- or
606 * -{text}- in which case no conversion should take place for text
607 *
608 * @param $text String: text to be converted
609 * @return String: converted text
610 */
611 public function convert( $text ) {
612 $variant = $this->getPreferredVariant();
613 return $this->convertTo( $text, $variant );
614 }
615
616 /**
617 * Same as convert() except a extra parameter to custom variant.
618 *
619 * @param $text String: text to be converted
620 * @param $variant String: the target variant code
621 * @return String: converted text
622 */
623 public function convertTo( $text, $variant ) {
624 global $wgDisableLangConversion;
625 if ( $wgDisableLangConversion ) {
626 return $text;
627 }
628 // Reset converter state for a new converter run.
629 $this->mConvRuleTitle = false;
630 return $this->recursiveConvertTopLevel( $text, $variant );
631 }
632
633 /**
634 * Recursively convert text on the outside. Allow to use nested
635 * markups to custom rules.
636 *
637 * @param $text String: text to be converted
638 * @param $variant String: the target variant code
639 * @param $depth Integer: depth of recursion
640 * @return String: converted text
641 */
642 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
643 $startPos = 0;
644 $out = '';
645 $length = strlen( $text );
646 $shouldConvert = !$this->guessVariant( $text, $variant );
647
648 while ( $startPos < $length ) {
649 $pos = strpos( $text, '-{', $startPos );
650
651 if ( $pos === false ) {
652 // No more markup, append final segment
653 $fragment = substr( $text, $startPos );
654 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
655 return $out;
656 }
657
658 // Markup found
659 // Append initial segment
660 $fragment = substr( $text, $startPos, $pos - $startPos );
661 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
662
663 // Advance position
664 $startPos = $pos;
665
666 // Do recursive conversion
667 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
668 }
669
670 return $out;
671 }
672
673 /**
674 * Recursively convert text on the inside.
675 *
676 * @param $text String: text to be converted
677 * @param $variant String: the target variant code
678 * @param $startPos int
679 * @param $depth Integer: depth of recursion
680 *
681 * @throws MWException
682 * @return String: converted text
683 */
684 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
685 // Quick sanity check (no function calls)
686 if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
687 throw new MWException( __METHOD__ . ': invalid input string' );
688 }
689
690 $startPos += 2;
691 $inner = '';
692 $warningDone = false;
693 $length = strlen( $text );
694
695 while ( $startPos < $length ) {
696 $m = false;
697 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
698 if ( !$m ) {
699 // Unclosed rule
700 break;
701 }
702
703 $token = $m[0][0];
704 $pos = $m[0][1];
705
706 // Markup found
707 // Append initial segment
708 $inner .= substr( $text, $startPos, $pos - $startPos );
709
710 // Advance position
711 $startPos = $pos;
712
713 switch ( $token ) {
714 case '-{':
715 // Check max depth
716 if ( $depth >= $this->mMaxDepth ) {
717 $inner .= '-{';
718 if ( !$warningDone ) {
719 $inner .= '<span class="error">' .
720 wfMessage( 'language-converter-depth-warning' )
721 ->numParams( $this->mMaxDepth )->inContentLanguage()->text() .
722 '</span>';
723 $warningDone = true;
724 }
725 $startPos += 2;
726 continue;
727 }
728 // Recursively parse another rule
729 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
730 break;
731 case '}-':
732 // Apply the rule
733 $startPos += 2;
734 $rule = new ConverterRule( $inner, $this );
735 $rule->parse( $variant );
736 $this->applyManualConv( $rule );
737 return $rule->getDisplay();
738 default:
739 throw new MWException( __METHOD__ . ': invalid regex match' );
740 }
741 }
742
743 // Unclosed rule
744 if ( $startPos < $length ) {
745 $inner .= substr( $text, $startPos );
746 }
747 $startPos = $length;
748 return '-{' . $this->autoConvert( $inner, $variant );
749 }
750
751 /**
752 * If a language supports multiple variants, it is possible that
753 * non-existing link in one variant actually exists in another variant.
754 * This function tries to find it. See e.g. LanguageZh.php
755 *
756 * @param $link String: the name of the link
757 * @param $nt Mixed: the title object of the link
758 * @param $ignoreOtherCond Boolean: to disable other conditions when
759 * we need to transclude a template or update a category's link
760 * @return Null, the input parameters may be modified upon return
761 */
762 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
763 # If the article has already existed, there is no need to
764 # check it again, otherwise it may cause a fault.
765 if ( is_object( $nt ) && $nt->exists() ) {
766 return;
767 }
768
769 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
770 $wgUser;
771 $isredir = $wgRequest->getText( 'redirect', 'yes' );
772 $action = $wgRequest->getText( 'action' );
773 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
774 $disableLinkConversion = $wgDisableLangConversion
775 || $wgDisableTitleConversion;
776 $linkBatch = new LinkBatch();
777
778 $ns = NS_MAIN;
779
780 if ( $disableLinkConversion ||
781 ( !$ignoreOtherCond &&
782 ( $isredir == 'no'
783 || $action == 'edit'
784 || $action == 'submit'
785 || $linkconvert == 'no'
786 || $wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
787 return;
788 }
789
790 if ( is_object( $nt ) ) {
791 $ns = $nt->getNamespace();
792 }
793
794 $variants = $this->autoConvertToAllVariants( $link );
795 if ( !$variants ) { // give up
796 return;
797 }
798
799 $titles = array();
800
801 foreach ( $variants as $v ) {
802 if ( $v != $link ) {
803 $varnt = Title::newFromText( $v, $ns );
804 if ( !is_null( $varnt ) ) {
805 $linkBatch->addObj( $varnt );
806 $titles[] = $varnt;
807 }
808 }
809 }
810
811 // fetch all variants in single query
812 $linkBatch->execute();
813
814 foreach ( $titles as $varnt ) {
815 if ( $varnt->getArticleID() > 0 ) {
816 $nt = $varnt;
817 $link = $varnt->getText();
818 break;
819 }
820 }
821 }
822
823 /**
824 * Returns language specific hash options.
825 *
826 * @return string
827 */
828 public function getExtraHashOptions() {
829 $variant = $this->getPreferredVariant();
830 return '!' . $variant;
831 }
832
833 /**
834 * Guess if a text is written in a variant. This should be implemented in subclasses.
835 *
836 * @param string $text the text to be checked
837 * @param string $variant language code of the variant to be checked for
838 * @return bool true if $text appears to be written in $variant, false if not
839 *
840 * @author Nikola Smolenski <smolensk@eunet.rs>
841 * @since 1.19
842 */
843 public function guessVariant( $text, $variant ) {
844 return false;
845 }
846
847 /**
848 * Load default conversion tables.
849 * This method must be implemented in derived class.
850 *
851 * @private
852 * @throws MWException
853 */
854 function loadDefaultTables() {
855 $name = get_class( $this );
856 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
857 }
858
859 /**
860 * Load conversion tables either from the cache or the disk.
861 * @private
862 * @param $fromCache Boolean: load from memcached? Defaults to true.
863 */
864 function loadTables( $fromCache = true ) {
865 global $wgLangConvMemc;
866
867 if ( $this->mTablesLoaded ) {
868 return;
869 }
870
871 wfProfileIn( __METHOD__ );
872 $this->mTablesLoaded = true;
873 $this->mTables = false;
874 if ( $fromCache ) {
875 wfProfileIn( __METHOD__ . '-cache' );
876 $this->mTables = $wgLangConvMemc->get( $this->mCacheKey );
877 wfProfileOut( __METHOD__ . '-cache' );
878 }
879 if ( !$this->mTables
880 || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
881 wfProfileIn( __METHOD__ . '-recache' );
882 // not in cache, or we need a fresh reload.
883 // We will first load the default tables
884 // then update them using things in MediaWiki:Conversiontable/*
885 $this->loadDefaultTables();
886 foreach ( $this->mVariants as $var ) {
887 $cached = $this->parseCachedTable( $var );
888 $this->mTables[$var]->mergeArray( $cached );
889 }
890
891 $this->postLoadTables();
892 $this->mTables[self::CACHE_VERSION_KEY] = true;
893
894 $wgLangConvMemc->set( $this->mCacheKey, $this->mTables, 43200 );
895 wfProfileOut( __METHOD__ . '-recache' );
896 }
897 wfProfileOut( __METHOD__ );
898 }
899
900 /**
901 * Hook for post processing after conversion tables are loaded.
902 */
903 function postLoadTables() { }
904
905 /**
906 * Reload the conversion tables.
907 *
908 * @private
909 */
910 function reloadTables() {
911 if ( $this->mTables ) {
912 unset( $this->mTables );
913 }
914 $this->mTablesLoaded = false;
915 $this->loadTables( false );
916 }
917
918 /**
919 * Parse the conversion table stored in the cache.
920 *
921 * The tables should be in blocks of the following form:
922 * -{
923 * word => word ;
924 * word => word ;
925 * ...
926 * }-
927 *
928 * To make the tables more manageable, subpages are allowed
929 * and will be parsed recursively if $recursive == true.
930 *
931 * @param $code String: language code
932 * @param $subpage String: subpage name
933 * @param $recursive Boolean: parse subpages recursively? Defaults to true.
934 *
935 * @return array
936 */
937 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
938 static $parsed = array();
939
940 $key = 'Conversiontable/' . $code;
941 if ( $subpage ) {
942 $key .= '/' . $subpage;
943 }
944 if ( array_key_exists( $key, $parsed ) ) {
945 return array();
946 }
947
948 $parsed[$key] = true;
949
950 if ( $subpage === '' ) {
951 $txt = MessageCache::singleton()->getMsgFromNamespace( $key, $code );
952 } else {
953 $txt = false;
954 $title = Title::makeTitleSafe( NS_MEDIAWIKI, $key );
955 if ( $title && $title->exists() ) {
956 $revision = Revision::newFromTitle( $title );
957 if ( $revision ) {
958 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT ) {
959 $txt = $revision->getContent( Revision::RAW )->getNativeData();
960 }
961
962 // @todo in the future, use a specialized content model, perhaps based on json!
963 }
964 }
965 }
966
967 # Nothing to parse if there's no text
968 if ( $txt === false || $txt === null || $txt === '' ) {
969 return array();
970 }
971
972 // get all subpage links of the form
973 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
974 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
975 ':Conversiontable';
976 $subs = StringUtils::explode( '[[', $txt );
977 $sublinks = array();
978 foreach ( $subs as $sub ) {
979 $link = explode( ']]', $sub, 2 );
980 if ( count( $link ) != 2 ) {
981 continue;
982 }
983 $b = explode( '|', $link[0], 2 );
984 $b = explode( '/', trim( $b[0] ), 3 );
985 if ( count( $b ) == 3 ) {
986 $sublink = $b[2];
987 } else {
988 $sublink = '';
989 }
990
991 if ( $b[0] == $linkhead && $b[1] == $code ) {
992 $sublinks[] = $sublink;
993 }
994 }
995
996 // parse the mappings in this page
997 $blocks = StringUtils::explode( '-{', $txt );
998 $ret = array();
999 $first = true;
1000 foreach ( $blocks as $block ) {
1001 if ( $first ) {
1002 // Skip the part before the first -{
1003 $first = false;
1004 continue;
1005 }
1006 $mappings = explode( '}-', $block, 2 );
1007 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
1008 $mappings[0] );
1009 $table = StringUtils::explode( ';', $stripped );
1010 foreach ( $table as $t ) {
1011 $m = explode( '=>', $t, 3 );
1012 if ( count( $m ) != 2 ) {
1013 continue;
1014 }
1015 // trim any trailling comments starting with '//'
1016 $tt = explode( '//', $m[1], 2 );
1017 $ret[trim( $m[0] )] = trim( $tt[0] );
1018 }
1019 }
1020
1021 // recursively parse the subpages
1022 if ( $recursive ) {
1023 foreach ( $sublinks as $link ) {
1024 $s = $this->parseCachedTable( $code, $link, $recursive );
1025 $ret = array_merge( $ret, $s );
1026 }
1027 }
1028
1029 if ( $this->mUcfirst ) {
1030 foreach ( $ret as $k => $v ) {
1031 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
1032 }
1033 }
1034 return $ret;
1035 }
1036
1037 /**
1038 * Enclose a string with the "no conversion" tag. This is used by
1039 * various functions in the Parser.
1040 *
1041 * @param $text String: text to be tagged for no conversion
1042 * @param $noParse Boolean: unused
1043 * @return String: the tagged text
1044 */
1045 public function markNoConversion( $text, $noParse = false ) {
1046 # don't mark if already marked
1047 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
1048 return $text;
1049 }
1050
1051 $ret = "-{R|$text}-";
1052 return $ret;
1053 }
1054
1055 /**
1056 * Convert the sorting key for category links. This should make different
1057 * keys that are variants of each other map to the same key.
1058 *
1059 * @param $key string
1060 *
1061 * @return string
1062 */
1063 function convertCategoryKey( $key ) {
1064 return $key;
1065 }
1066
1067 /**
1068 * Hook to refresh the cache of conversion tables when
1069 * MediaWiki:Conversiontable* is updated.
1070 * @private
1071 *
1072 * @param $page WikiPage object
1073 * @param $user Object: User object for the current user
1074 * @param $content Content: new page content
1075 * @param $summary String: edit summary of the edit
1076 * @param $isMinor Boolean: was the edit marked as minor?
1077 * @param $isWatch Boolean: did the user watch this page or not?
1078 * @param $section
1079 * @param $flags int Bitfield
1080 * @param $revision Object: new Revision object or null
1081 * @return Boolean: true
1082 */
1083 function OnPageContentSaveComplete( $page, $user, $content, $summary, $isMinor,
1084 $isWatch, $section, $flags, $revision ) {
1085 $titleobj = $page->getTitle();
1086 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
1087 $title = $titleobj->getDBkey();
1088 $t = explode( '/', $title, 3 );
1089 $c = count( $t );
1090 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1091 if ( $this->validateVariant( $t[1] ) ) {
1092 $this->reloadTables();
1093 }
1094 }
1095 }
1096 return true;
1097 }
1098
1099 /**
1100 * Armour rendered math against conversion.
1101 * Escape special chars in parsed math text. (in most cases are img elements)
1102 *
1103 * @param $text String: text to armour against conversion
1104 * @return String: armoured text where { and } have been converted to
1105 * &#123; and &#125;
1106 * @deprecated since 1.22 is no longer used
1107 */
1108 public function armourMath( $text ) {
1109 // convert '-{' and '}-' to '-&#123;' and '&#125;-' to prevent
1110 // any unwanted markup appearing in the math image tag.
1111 $text = strtr( $text, array( '-{' => '-&#123;', '}-' => '&#125;-' ) );
1112 return $text;
1113 }
1114
1115 /**
1116 * Get the cached separator pattern for ConverterRule::parseRules()
1117 */
1118 function getVarSeparatorPattern() {
1119 if ( is_null( $this->mVarSeparatorPattern ) ) {
1120 // varsep_pattern for preg_split:
1121 // text should be splited by ";" only if a valid variant
1122 // name exist after the markup, for example:
1123 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1124 // <span style="font-size:120%;">yyy</span>;}-
1125 // we should split it as:
1126 // array(
1127 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1128 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1129 // [2] => ''
1130 // )
1131 $pat = '/;\s*(?=';
1132 foreach ( $this->mVariants as $variant ) {
1133 // zh-hans:xxx;zh-hant:yyy
1134 $pat .= $variant . '\s*:|';
1135 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1136 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1137 }
1138 $pat .= '\s*$)/';
1139 $this->mVarSeparatorPattern = $pat;
1140 }
1141 return $this->mVarSeparatorPattern;
1142 }
1143 }
1144
1145 /**
1146 * Parser for rules of language conversion , parse rules in -{ }- tag.
1147 * @ingroup Language
1148 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1149 */
1150 class ConverterRule {
1151 public $mText; // original text in -{text}-
1152 public $mConverter; // LanguageConverter object
1153 public $mRuleDisplay = '';
1154 public $mRuleTitle = false;
1155 public $mRules = '';// string : the text of the rules
1156 public $mRulesAction = 'none';
1157 public $mFlags = array();
1158 public $mVariantFlags = array();
1159 public $mConvTable = array();
1160 public $mBidtable = array();// array of the translation in each variant
1161 public $mUnidtable = array();// array of the translation in each variant
1162
1163 /**
1164 * Constructor
1165 *
1166 * @param $text String: the text between -{ and }-
1167 * @param $converter LanguageConverter object
1168 */
1169 public function __construct( $text, $converter ) {
1170 $this->mText = $text;
1171 $this->mConverter = $converter;
1172 }
1173
1174 /**
1175 * Check if variants array in convert array.
1176 *
1177 * @param $variants Array or string: variant language code
1178 * @return String: translated text
1179 */
1180 public function getTextInBidtable( $variants ) {
1181 $variants = (array)$variants;
1182 if ( !$variants ) {
1183 return false;
1184 }
1185 foreach ( $variants as $variant ) {
1186 if ( isset( $this->mBidtable[$variant] ) ) {
1187 return $this->mBidtable[$variant];
1188 }
1189 }
1190 return false;
1191 }
1192
1193 /**
1194 * Parse flags with syntax -{FLAG| ... }-
1195 * @private
1196 */
1197 function parseFlags() {
1198 $text = $this->mText;
1199 $flags = array();
1200 $variantFlags = array();
1201
1202 $sepPos = strpos( $text, '|' );
1203 if ( $sepPos !== false ) {
1204 $validFlags = $this->mConverter->mFlags;
1205 $f = StringUtils::explode( ';', substr( $text, 0, $sepPos ) );
1206 foreach ( $f as $ff ) {
1207 $ff = trim( $ff );
1208 if ( isset( $validFlags[$ff] ) ) {
1209 $flags[$validFlags[$ff]] = true;
1210 }
1211 }
1212 $text = strval( substr( $text, $sepPos + 1 ) );
1213 }
1214
1215 if ( !$flags ) {
1216 $flags['S'] = true;
1217 } elseif ( isset( $flags['R'] ) ) {
1218 $flags = array( 'R' => true );// remove other flags
1219 } elseif ( isset( $flags['N'] ) ) {
1220 $flags = array( 'N' => true );// remove other flags
1221 } elseif ( isset( $flags['-'] ) ) {
1222 $flags = array( '-' => true );// remove other flags
1223 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1224 $flags['H'] = true;
1225 } elseif ( isset( $flags['H'] ) ) {
1226 // replace A flag, and remove other flags except T
1227 $temp = array( '+' => true, 'H' => true );
1228 if ( isset( $flags['T'] ) ) {
1229 $temp['T'] = true;
1230 }
1231 if ( isset( $flags['D'] ) ) {
1232 $temp['D'] = true;
1233 }
1234 $flags = $temp;
1235 } else {
1236 if ( isset( $flags['A'] ) ) {
1237 $flags['+'] = true;
1238 $flags['S'] = true;
1239 }
1240 if ( isset( $flags['D'] ) ) {
1241 unset( $flags['S'] );
1242 }
1243 // try to find flags like "zh-hans", "zh-hant"
1244 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1245 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter->mVariants );
1246 if ( $variantFlags ) {
1247 $variantFlags = array_flip( $variantFlags );
1248 $flags = array();
1249 }
1250 }
1251 $this->mVariantFlags = $variantFlags;
1252 $this->mRules = $text;
1253 $this->mFlags = $flags;
1254 }
1255
1256 /**
1257 * Generate conversion table.
1258 * @private
1259 */
1260 function parseRules() {
1261 $rules = $this->mRules;
1262 $bidtable = array();
1263 $unidtable = array();
1264 $variants = $this->mConverter->mVariants;
1265 $varsep_pattern = $this->mConverter->getVarSeparatorPattern();
1266
1267 // Split according to $varsep_pattern, but ignore semicolons from HTML entities
1268 $rules = preg_replace( '/(&[#a-zA-Z0-9]+);/', "$1\x01", $rules );
1269 $choice = preg_split( $varsep_pattern, $rules );
1270 $choice = str_replace( "\x01", ';', $choice );
1271
1272 foreach ( $choice as $c ) {
1273 $v = explode( ':', $c, 2 );
1274 if ( count( $v ) != 2 ) {
1275 // syntax error, skip
1276 continue;
1277 }
1278 $to = trim( $v[1] );
1279 $v = trim( $v[0] );
1280 $u = explode( '=>', $v, 2 );
1281 // if $to is empty, strtr() could return a wrong result
1282 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1283 $bidtable[$v] = $to;
1284 } elseif ( count( $u ) == 2 ) {
1285 $from = trim( $u[0] );
1286 $v = trim( $u[1] );
1287 if ( array_key_exists( $v, $unidtable )
1288 && !is_array( $unidtable[$v] )
1289 && $to
1290 && in_array( $v, $variants ) ) {
1291 $unidtable[$v] = array( $from => $to );
1292 } elseif ( $to && in_array( $v, $variants ) ) {
1293 $unidtable[$v][$from] = $to;
1294 }
1295 }
1296 // syntax error, pass
1297 if ( !isset( $this->mConverter->mVariantNames[$v] ) ) {
1298 $bidtable = array();
1299 $unidtable = array();
1300 break;
1301 }
1302 }
1303 $this->mBidtable = $bidtable;
1304 $this->mUnidtable = $unidtable;
1305 }
1306
1307 /**
1308 * @private
1309 *
1310 * @return string
1311 */
1312 function getRulesDesc() {
1313 $codesep = $this->mConverter->mDescCodeSep;
1314 $varsep = $this->mConverter->mDescVarSep;
1315 $text = '';
1316 foreach ( $this->mBidtable as $k => $v ) {
1317 $text .= $this->mConverter->mVariantNames[$k] . "$codesep$v$varsep";
1318 }
1319 foreach ( $this->mUnidtable as $k => $a ) {
1320 foreach ( $a as $from => $to ) {
1321 $text .= $from . '⇒' . $this->mConverter->mVariantNames[$k] .
1322 "$codesep$to$varsep";
1323 }
1324 }
1325 return $text;
1326 }
1327
1328 /**
1329 * Parse rules conversion.
1330 * @private
1331 *
1332 * @param $variant
1333 *
1334 * @return string
1335 */
1336 function getRuleConvertedStr( $variant ) {
1337 $bidtable = $this->mBidtable;
1338 $unidtable = $this->mUnidtable;
1339
1340 if ( count( $bidtable ) + count( $unidtable ) == 0 ) {
1341 return $this->mRules;
1342 } else {
1343 // display current variant in bidirectional array
1344 $disp = $this->getTextInBidtable( $variant );
1345 // or display current variant in fallbacks
1346 if ( !$disp ) {
1347 $disp = $this->getTextInBidtable(
1348 $this->mConverter->getVariantFallbacks( $variant ) );
1349 }
1350 // or display current variant in unidirectional array
1351 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1352 $disp = array_values( $unidtable[$variant] );
1353 $disp = $disp[0];
1354 }
1355 // or display frist text under disable manual convert
1356 if ( !$disp
1357 && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
1358 if ( count( $bidtable ) > 0 ) {
1359 $disp = array_values( $bidtable );
1360 $disp = $disp[0];
1361 } else {
1362 $disp = array_values( $unidtable );
1363 $disp = array_values( $disp[0] );
1364 $disp = $disp[0];
1365 }
1366 }
1367 return $disp;
1368 }
1369 }
1370
1371 /**
1372 * Similar to getRuleConvertedStr(), but this prefers to use original
1373 * page title if $variant === $this->mConverter->mMainLanguageCode
1374 * and may return false in this case (so this title conversion rule
1375 * will be ignored and the original title is shown).
1376 *
1377 * @since 1.22
1378 * @param $variant The variant code to display page title in
1379 * @return String|false The converted title or false if just page name
1380 */
1381 function getRuleConvertedTitle( $variant ) {
1382 if ( $variant === $this->mConverter->mMainLanguageCode ) {
1383 // If a string targeting exactly this variant is set,
1384 // use it. Otherwise, just return false, so the real
1385 // page name can be shown (and because variant === main,
1386 // there'll be no further automatic conversion).
1387 $disp = $this->getTextInBidtable( $variant );
1388 if ( $disp ) {
1389 return $disp;
1390 }
1391 if ( array_key_exists( $variant, $this->mUnidtable ) ) {
1392 $disp = array_values( $this->mUnidtable[$variant] );
1393 $disp = $disp[0];
1394 }
1395 // Assigned above or still false.
1396 return $disp;
1397 } else {
1398 return $this->getRuleConvertedStr( $variant );
1399 }
1400 }
1401
1402 /**
1403 * Generate conversion table for all text.
1404 * @private
1405 */
1406 function generateConvTable() {
1407 // Special case optimisation
1408 if ( !$this->mBidtable && !$this->mUnidtable ) {
1409 $this->mConvTable = array();
1410 return;
1411 }
1412
1413 $bidtable = $this->mBidtable;
1414 $unidtable = $this->mUnidtable;
1415 $manLevel = $this->mConverter->mManualLevel;
1416
1417 $vmarked = array();
1418 foreach ( $this->mConverter->mVariants as $v ) {
1419 /* for bidirectional array
1420 fill in the missing variants, if any,
1421 with fallbacks */
1422 if ( !isset( $bidtable[$v] ) ) {
1423 $variantFallbacks =
1424 $this->mConverter->getVariantFallbacks( $v );
1425 $vf = $this->getTextInBidtable( $variantFallbacks );
1426 if ( $vf ) {
1427 $bidtable[$v] = $vf;
1428 }
1429 }
1430
1431 if ( isset( $bidtable[$v] ) ) {
1432 foreach ( $vmarked as $vo ) {
1433 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1434 // or -{H|zh:WordZh;zh-tw:WordTw}-
1435 // or -{-|zh:WordZh;zh-tw:WordTw}-
1436 // to introduce a custom mapping between
1437 // words WordZh and WordTw in the whole text
1438 if ( $manLevel[$v] == 'bidirectional' ) {
1439 $this->mConvTable[$v][$bidtable[$vo]] = $bidtable[$v];
1440 }
1441 if ( $manLevel[$vo] == 'bidirectional' ) {
1442 $this->mConvTable[$vo][$bidtable[$v]] = $bidtable[$vo];
1443 }
1444 }
1445 $vmarked[] = $v;
1446 }
1447 /* for unidirectional array fill to convert tables */
1448 if ( ( $manLevel[$v] == 'bidirectional' || $manLevel[$v] == 'unidirectional' )
1449 && isset( $unidtable[$v] ) )
1450 {
1451 if ( isset( $this->mConvTable[$v] ) ) {
1452 $this->mConvTable[$v] = array_merge( $this->mConvTable[$v], $unidtable[$v] );
1453 } else {
1454 $this->mConvTable[$v] = $unidtable[$v];
1455 }
1456 }
1457 }
1458 }
1459
1460 /**
1461 * Parse rules and flags.
1462 * @param $variant String: variant language code
1463 */
1464 public function parse( $variant = null ) {
1465 if ( !$variant ) {
1466 $variant = $this->mConverter->getPreferredVariant();
1467 }
1468
1469 $this->parseFlags();
1470 $flags = $this->mFlags;
1471
1472 // convert to specified variant
1473 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1474 if ( $this->mVariantFlags ) {
1475 // check if current variant in flags
1476 if ( isset( $this->mVariantFlags[$variant] ) ) {
1477 // then convert <text to convert> to current language
1478 $this->mRules = $this->mConverter->autoConvert( $this->mRules,
1479 $variant );
1480 } else { // if current variant no in flags,
1481 // then we check its fallback variants.
1482 $variantFallbacks =
1483 $this->mConverter->getVariantFallbacks( $variant );
1484 if ( is_array( $variantFallbacks ) ) {
1485 foreach ( $variantFallbacks as $variantFallback ) {
1486 // if current variant's fallback exist in flags
1487 if ( isset( $this->mVariantFlags[$variantFallback] ) ) {
1488 // then convert <text to convert> to fallback language
1489 $this->mRules =
1490 $this->mConverter->autoConvert( $this->mRules,
1491 $variantFallback );
1492 break;
1493 }
1494 }
1495 }
1496 }
1497 $this->mFlags = $flags = array( 'R' => true );
1498 }
1499
1500 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1501 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1502 $this->mRules = str_replace( '=&gt;', '=>', $this->mRules );
1503 $this->parseRules();
1504 }
1505 $rules = $this->mRules;
1506
1507 if ( !$this->mBidtable && !$this->mUnidtable ) {
1508 if ( isset( $flags['+'] ) || isset( $flags['-'] ) ) {
1509 // fill all variants if text in -{A/H/-|text} without rules
1510 foreach ( $this->mConverter->mVariants as $v ) {
1511 $this->mBidtable[$v] = $rules;
1512 }
1513 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1514 $this->mFlags = $flags = array( 'R' => true );
1515 }
1516 }
1517
1518 $this->mRuleDisplay = false;
1519 foreach ( $flags as $flag => $unused ) {
1520 switch ( $flag ) {
1521 case 'R':
1522 // if we don't do content convert, still strip the -{}- tags
1523 $this->mRuleDisplay = $rules;
1524 break;
1525 case 'N':
1526 // process N flag: output current variant name
1527 $ruleVar = trim( $rules );
1528 if ( isset( $this->mConverter->mVariantNames[$ruleVar] ) ) {
1529 $this->mRuleDisplay = $this->mConverter->mVariantNames[$ruleVar];
1530 } else {
1531 $this->mRuleDisplay = '';
1532 }
1533 break;
1534 case 'D':
1535 // process D flag: output rules description
1536 $this->mRuleDisplay = $this->getRulesDesc();
1537 break;
1538 case 'H':
1539 // process H,- flag or T only: output nothing
1540 $this->mRuleDisplay = '';
1541 break;
1542 case '-':
1543 $this->mRulesAction = 'remove';
1544 $this->mRuleDisplay = '';
1545 break;
1546 case '+':
1547 $this->mRulesAction = 'add';
1548 $this->mRuleDisplay = '';
1549 break;
1550 case 'S':
1551 $this->mRuleDisplay = $this->getRuleConvertedStr( $variant );
1552 break;
1553 case 'T':
1554 $this->mRuleTitle = $this->getRuleConvertedTitle( $variant );
1555 $this->mRuleDisplay = '';
1556 break;
1557 default:
1558 // ignore unknown flags (but see error case below)
1559 }
1560 }
1561 if ( $this->mRuleDisplay === false ) {
1562 $this->mRuleDisplay = '<span class="error">'
1563 . wfMessage( 'converter-manual-rule-error' )->inContentLanguage()->escaped()
1564 . '</span>';
1565 }
1566
1567 $this->generateConvTable();
1568 }
1569
1570 /**
1571 * @todo FIXME: code this function :)
1572 */
1573 public function hasRules() {
1574 // TODO:
1575 }
1576
1577 /**
1578 * Get display text on markup -{...}-
1579 * @return string
1580 */
1581 public function getDisplay() {
1582 return $this->mRuleDisplay;
1583 }
1584
1585 /**
1586 * Get converted title.
1587 * @return string
1588 */
1589 public function getTitle() {
1590 return $this->mRuleTitle;
1591 }
1592
1593 /**
1594 * Return how deal with conversion rules.
1595 * @return string
1596 */
1597 public function getRulesAction() {
1598 return $this->mRulesAction;
1599 }
1600
1601 /**
1602 * Get conversion table. (bidirectional and unidirectional
1603 * conversion table)
1604 * @return array
1605 */
1606 public function getConvTable() {
1607 return $this->mConvTable;
1608 }
1609
1610 /**
1611 * Get conversion rules string.
1612 * @return string
1613 */
1614 public function getRules() {
1615 return $this->mRules;
1616 }
1617
1618 /**
1619 * Get conversion flags.
1620 * @return array
1621 */
1622 public function getFlags() {
1623 return $this->mFlags;
1624 }
1625 }