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