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