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