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