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