Follow-up r90369: Add third parameter to filetype-unwanted-type (for PLURAL)
[mediawiki.git] / languages / LanguageConverter.php
blob0abab57b0fd9ddee507b11a93d8075b0eb54d7ff
1 <?php
2 /**
3 * Contains the LanguageConverter class and ConverterRule class
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.
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.
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
20 * @file
21 * @ingroup Language
24 /**
25 * Base class for language conversion.
26 * @ingroup Language
28 * @author Zhengzhu Feng <zhengzhu@gmail.com>
29 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>, PhiLiP <philip.npc@gmail.com>
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;
39 /**
40 * @var String: memcached key name
42 var $mCacheKey;
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;
55 const CACHE_VERSION_KEY = 'VERSION 6';
57 /**
58 * Constructor
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
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::getLanguageNames();
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
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';
98 $this->mFlags[$v] = $v;
103 * Get all valid variants.
104 * Call this instead of using $this->mVariants directly.
106 * @return Array: contains all valid variants
108 public function getVariants() {
109 return $this->mVariants;
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.
119 * @param $variant String: the language code of the variant
120 * @return String: The code of the fallback language or the
121 * main code if there is no fallback
123 public function getVariantFallbacks( $variant ) {
124 if ( isset( $this->mVariantFallbacks[$variant] ) ) {
125 return $this->mVariantFallbacks[$variant];
127 return $this->mMainLanguageCode;
131 * Get the title produced by the conversion rule.
132 * @return String: The converted title text
134 public function getConvRuleTitle() {
135 return $this->mConvRuleTitle;
139 * Get preferred language variant.
140 * @return String: the preferred language code
142 public function getPreferredVariant() {
143 global $wgDefaultLanguageVariant, $wgUser;
145 $req = $this->getURLVariant();
147 if ( $wgUser->isLoggedIn() && !$req ) {
148 $req = $this->getUserVariant();
149 } elseif ( !$req ) {
150 $req = $this->getHeaderVariant();
153 if ( $wgDefaultLanguageVariant && !$req ) {
154 $req = $this->validateVariant( $wgDefaultLanguageVariant );
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 ( $req ) {
162 return $req;
164 return $this->mMainLanguageCode;
168 * Get default variant.
169 * This function would not be affected by user's settings or headers
170 * @return String: the default variant code
172 public function getDefaultVariant() {
173 global $wgDefaultLanguageVariant;
175 $req = $this->getURLVariant();
177 if ( $wgDefaultLanguageVariant && !$req ) {
178 $req = $this->validateVariant( $wgDefaultLanguageVariant );
181 if ( $req ) {
182 return $req;
184 return $this->mMainLanguageCode;
188 * Validate the variant
189 * @param $variant String: the variant to validate
190 * @return Mixed: returns the variant if it is valid, null otherwise
192 protected function validateVariant( $variant = null ) {
193 if ( $variant !== null && in_array( $variant, $this->mVariants ) ) {
194 return $variant;
196 return null;
200 * Get the variant specified in the URL
202 * @return Mixed: variant if one found, false otherwise.
204 public function getURLVariant() {
205 global $wgRequest;
207 if ( $this->mURLVariant ) {
208 return $this->mURLVariant;
211 // see if the preference is set in the request
212 $ret = $wgRequest->getText( 'variant' );
214 if ( !$ret ) {
215 $ret = $wgRequest->getVal( 'uselang' );
218 return $this->mURLVariant = $this->validateVariant( $ret );
222 * Determine if the user has a variant set.
224 * @return Mixed: variant if one found, false otherwise.
226 protected function getUserVariant() {
227 global $wgUser;
229 // memoizing this function wreaks havoc on parserTest.php
231 if ( $this->mUserVariant ) {
232 return $this->mUserVariant;
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' );
247 return $this->mUserVariant = $this->validateVariant( $ret );
251 * Determine the language variant from the Accept-Language header.
253 * @return Mixed: variant if one found, false otherwise.
255 protected function getHeaderVariant() {
256 global $wgRequest;
258 if ( $this->mHeaderVariant ) {
259 return $this->mHeaderVariant;
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;
269 $fallbackLanguages = array();
270 foreach ( $languages as $language ) {
271 $this->mHeaderVariant = $this->validateVariant( $language );
272 if ( $this->mHeaderVariant ) {
273 break;
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 );
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;
299 return $this->mHeaderVariant;
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().
308 * @param $text String the text to be converted
309 * @param $toVariant bool|string the target language code
310 * @return String the converted text
312 public function autoConvert( $text, $toVariant = false ) {
313 wfProfileIn( __METHOD__ );
315 $this->loadTables();
317 if ( !$toVariant ) {
318 $toVariant = $this->getPreferredVariant();
319 if ( !$toVariant ) {
320 wfProfileOut( __METHOD__ );
321 return $text;
325 if( $this->guessVariant( $text, $toVariant ) ) {
326 return $text;
329 /* we convert everything except:
330 1. HTML markups (anything between < and >)
331 2. HTML entities
332 3. placeholders created by the parser
334 global $wgParser;
335 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
336 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
337 } else {
338 $marker = '';
341 // this one is needed when the text is inside an HTML markup
342 $htmlfix = '|<[^>]+$|^[^<>]*>';
344 // disable convert to variants between <code></code> tags
345 $codefix = '<code>.+?<\/code>|';
346 // disable convertsion of <script type="text/javascript"> ... </script>
347 $scriptfix = '<script.*?>.*?<\/script>|';
348 // disable conversion of <pre xxxx> ... </pre>
349 $prefix = '<pre.*?>.*?<\/pre>|';
351 $reg = '/' . $codefix . $scriptfix . $prefix .
352 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
353 $startPos = 0;
354 $sourceBlob = '';
355 $literalBlob = '';
357 // Guard against delimiter nulls in the input
358 $text = str_replace( "\000", '', $text );
360 $markupMatches = null;
361 $elementMatches = null;
362 while ( $startPos < strlen( $text ) ) {
363 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
364 $elementPos = $markupMatches[0][1];
365 $element = $markupMatches[0][0];
366 } else {
367 $elementPos = strlen( $text );
368 $element = '';
371 // Queue the part before the markup for translation in a batch
372 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
374 // Advance to the next position
375 $startPos = $elementPos + strlen( $element );
377 // Translate any alt or title attributes inside the matched element
378 if ( $element !== '' && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element,
379 $elementMatches ) )
381 $attrs = Sanitizer::decodeTagAttributes( $elementMatches[2] );
382 $changed = false;
383 foreach ( array( 'title', 'alt' ) as $attrName ) {
384 if ( !isset( $attrs[$attrName] ) ) {
385 continue;
387 $attr = $attrs[$attrName];
388 // Don't convert URLs
389 if ( !strpos( $attr, '://' ) ) {
390 $attr = $this->translate( $attr, $toVariant );
393 // Remove HTML tags to avoid disrupting the layout
394 $attr = preg_replace( '/<[^>]+>/', '', $attr );
395 if ( $attr !== $attrs[$attrName] ) {
396 $attrs[$attrName] = $attr;
397 $changed = true;
400 if ( $changed ) {
401 $element = $elementMatches[1] . Html::expandAttributes( $attrs ) .
402 $elementMatches[3];
405 $literalBlob .= $element . "\000";
408 // Do the main translation batch
409 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
411 // Put the output back together
412 $translatedIter = StringUtils::explode( "\000", $translatedBlob );
413 $literalIter = StringUtils::explode( "\000", $literalBlob );
414 $output = '';
415 while ( $translatedIter->valid() && $literalIter->valid() ) {
416 $output .= $translatedIter->current();
417 $output .= $literalIter->current();
418 $translatedIter->next();
419 $literalIter->next();
422 wfProfileOut( __METHOD__ );
423 return $output;
427 * Translate a string to a variant.
428 * Doesn't parse rules or do any of that other stuff, for that use
429 * convert() or convertTo().
431 * @param $text String: text to convert
432 * @param $variant String: variant language code
433 * @return String: translated text
435 public function translate( $text, $variant ) {
436 wfProfileIn( __METHOD__ );
437 // If $text is empty or only includes spaces, do nothing
438 // Otherwise translate it
439 if ( trim( $text ) ) {
440 $this->loadTables();
441 $text = $this->mTables[$variant]->replace( $text );
443 wfProfileOut( __METHOD__ );
444 return $text;
448 * Call translate() to convert text to all valid variants.
450 * @param $text String: the text to be converted
451 * @return Array: variant => converted text
453 public function autoConvertToAllVariants( $text ) {
454 wfProfileIn( __METHOD__ );
455 $this->loadTables();
457 $ret = array();
458 foreach ( $this->mVariants as $variant ) {
459 $ret[$variant] = $this->translate( $text, $variant );
462 wfProfileOut( __METHOD__ );
463 return $ret;
467 * Convert link text to all valid variants.
468 * In the first, this function only convert text outside the
469 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
470 * titles, the text will get all converted always.
471 * So I removed this feature and deprecated the function.
473 * @param $text String: the text to be converted
474 * @return Array: variant => converted text
475 * @deprecated since 1.17 Use autoConvertToAllVariants() instead
477 public function convertLinkToAllVariants( $text ) {
478 return $this->autoConvertToAllVariants( $text );
482 * Apply manual conversion rules.
484 * @param $convRule ConverterRule Object of ConverterRule
486 protected function applyManualConv( $convRule ) {
487 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
488 // title conversion.
489 // Bug 24072: $mConvRuleTitle was overwritten by other manual
490 // rule(s) not for title, this breaks the title conversion.
491 $newConvRuleTitle = $convRule->getTitle();
492 if ( $newConvRuleTitle ) {
493 // So I add an empty check for getTitle()
494 $this->mConvRuleTitle = $newConvRuleTitle;
497 // merge/remove manual conversion rules to/from global table
498 $convTable = $convRule->getConvTable();
499 $action = $convRule->getRulesAction();
500 foreach ( $convTable as $variant => $pair ) {
501 if ( !$this->validateVariant( $variant ) ) {
502 continue;
505 if ( $action == 'add' ) {
506 foreach ( $pair as $from => $to ) {
507 // to ensure that $from and $to not be left blank
508 // so $this->translate() could always return a string
509 if ( $from || $to ) {
510 // more efficient than array_merge(), about 2.5 times.
511 $this->mTables[$variant]->setPair( $from, $to );
514 } elseif ( $action == 'remove' ) {
515 $this->mTables[$variant]->removeArray( $pair );
521 * Auto convert a Title object to a readable string in the
522 * preferred variant.
524 * @param $title Title a object of Title
525 * @return String: converted title text
527 public function convertTitle( $title ) {
528 $variant = $this->getPreferredVariant();
529 $index = $title->getNamespace();
530 if ( $index === NS_MAIN ) {
531 $text = '';
532 } else {
533 // first let's check if a message has given us a converted name
534 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
535 if ( $nsConvMsg->exists() ) {
536 $text = $nsConvMsg->plain();
537 } else {
538 // the message does not exist, try retrieve it from the current
539 // variant's namespace names.
540 $langObj = $this->mLangObj->factory( $variant );
541 $text = $langObj->getFormattedNsText( $index );
543 $text .= ':';
545 $text .= $title->getText();
546 $text = $this->translate( $text, $variant );
547 return $text;
551 * Convert text to different variants of a language. The automatic
552 * conversion is done in autoConvert(). Here we parse the text
553 * marked with -{}-, which specifies special conversions of the
554 * text that can not be accomplished in autoConvert().
556 * Syntax of the markup:
557 * -{code1:text1;code2:text2;...}- or
558 * -{flags|code1:text1;code2:text2;...}- or
559 * -{text}- in which case no conversion should take place for text
561 * @param $text String: text to be converted
562 * @return String: converted text
564 public function convert( $text ) {
565 $variant = $this->getPreferredVariant();
566 return $this->convertTo( $text, $variant );
570 * Same as convert() except a extra parameter to custom variant.
572 * @param $text String: text to be converted
573 * @param $variant String: the target variant code
574 * @return String: converted text
576 public function convertTo( $text, $variant ) {
577 global $wgDisableLangConversion;
578 if ( $wgDisableLangConversion || $this->guessVariant( $text, $variant ) ) {
579 return $text;
581 return $this->recursiveConvertTopLevel( $text, $variant );
585 * Recursively convert text on the outside. Allow to use nested
586 * markups to custom rules.
588 * @param $text String: text to be converted
589 * @param $variant String: the target variant code
590 * @param $depth Integer: depth of recursion
591 * @return String: converted text
593 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
594 $startPos = 0;
595 $out = '';
596 $length = strlen( $text );
597 while ( $startPos < $length ) {
598 $pos = strpos( $text, '-{', $startPos );
600 if ( $pos === false ) {
601 // No more markup, append final segment
602 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
603 return $out;
606 // Markup found
607 // Append initial segment
608 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
610 // Advance position
611 $startPos = $pos;
613 // Do recursive conversion
614 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
617 return $out;
621 * Recursively convert text on the inside.
623 * @param $text String: text to be converted
624 * @param $variant String: the target variant code
625 * @param $startPos int
626 * @param $depth Integer: depth of recursion
628 * @return String: converted text
630 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
631 // Quick sanity check (no function calls)
632 if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
633 throw new MWException( __METHOD__ . ': invalid input string' );
636 $startPos += 2;
637 $inner = '';
638 $warningDone = false;
639 $length = strlen( $text );
641 while ( $startPos < $length ) {
642 $m = false;
643 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
644 if ( !$m ) {
645 // Unclosed rule
646 break;
649 $token = $m[0][0];
650 $pos = $m[0][1];
652 // Markup found
653 // Append initial segment
654 $inner .= substr( $text, $startPos, $pos - $startPos );
656 // Advance position
657 $startPos = $pos;
659 switch ( $token ) {
660 case '-{':
661 // Check max depth
662 if ( $depth >= $this->mMaxDepth ) {
663 $inner .= '-{';
664 if ( !$warningDone ) {
665 $inner .= '<span class="error">' .
666 wfMsgForContent( 'language-converter-depth-warning',
667 $this->mMaxDepth ) .
668 '</span>';
669 $warningDone = true;
671 $startPos += 2;
672 continue;
674 // Recursively parse another rule
675 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
676 break;
677 case '}-':
678 // Apply the rule
679 $startPos += 2;
680 $rule = new ConverterRule( $inner, $this );
681 $rule->parse( $variant );
682 $this->applyManualConv( $rule );
683 return $rule->getDisplay();
684 default:
685 throw new MWException( __METHOD__ . ': invalid regex match' );
689 // Unclosed rule
690 if ( $startPos < $length ) {
691 $inner .= substr( $text, $startPos );
693 $startPos = $length;
694 return '-{' . $this->autoConvert( $inner, $variant );
698 * If a language supports multiple variants, it is possible that
699 * non-existing link in one variant actually exists in another variant.
700 * This function tries to find it. See e.g. LanguageZh.php
702 * @param $link String: the name of the link
703 * @param $nt Mixed: the title object of the link
704 * @param $ignoreOtherCond Boolean: to disable other conditions when
705 * we need to transclude a template or update a category's link
706 * @return Null, the input parameters may be modified upon return
708 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
709 # If the article has already existed, there is no need to
710 # check it again, otherwise it may cause a fault.
711 if ( is_object( $nt ) && $nt->exists() ) {
712 return;
715 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
716 $wgUser;
717 $isredir = $wgRequest->getText( 'redirect', 'yes' );
718 $action = $wgRequest->getText( 'action' );
719 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
720 $disableLinkConversion = $wgDisableLangConversion
721 || $wgDisableTitleConversion;
722 $linkBatch = new LinkBatch();
724 $ns = NS_MAIN;
726 if ( $disableLinkConversion ||
727 ( !$ignoreOtherCond &&
728 ( $isredir == 'no'
729 || $action == 'edit'
730 || $action == 'submit'
731 || $linkconvert == 'no'
732 || $wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
733 return;
736 if ( is_object( $nt ) ) {
737 $ns = $nt->getNamespace();
740 $variants = $this->autoConvertToAllVariants( $link );
741 if ( !$variants ) { // give up
742 return;
745 $titles = array();
747 foreach ( $variants as $v ) {
748 if ( $v != $link ) {
749 $varnt = Title::newFromText( $v, $ns );
750 if ( !is_null( $varnt ) ) {
751 $linkBatch->addObj( $varnt );
752 $titles[] = $varnt;
757 // fetch all variants in single query
758 $linkBatch->execute();
760 foreach ( $titles as $varnt ) {
761 if ( $varnt->getArticleID() > 0 ) {
762 $nt = $varnt;
763 $link = $varnt->getText();
764 break;
770 * Returns language specific hash options.
772 * @return string
774 public function getExtraHashOptions() {
775 $variant = $this->getPreferredVariant();
776 return '!' . $variant;
780 * Guess if a text is written in a variant. This should be implemented in subclasses.
782 * @param string $text the text to be checked
783 * @param string $variant language code of the variant to be checked for
784 * @return bool true if $text appears to be written in $variant, false if not
786 * @author Nikola Smolenski <smolensk@eunet.rs>
787 * @since 1.18
789 public function guessVariant($text, $variant) {
790 return false;
794 * Load default conversion tables.
795 * This method must be implemented in derived class.
797 * @private
799 function loadDefaultTables() {
800 $name = get_class( $this );
801 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
805 * Load conversion tables either from the cache or the disk.
806 * @private
807 * @param $fromCache Boolean: load from memcached? Defaults to true.
809 function loadTables( $fromCache = true ) {
810 if ( $this->mTablesLoaded ) {
811 return;
813 global $wgMemc;
814 wfProfileIn( __METHOD__ );
815 $this->mTablesLoaded = true;
816 $this->mTables = false;
817 if ( $fromCache ) {
818 wfProfileIn( __METHOD__ . '-cache' );
819 $this->mTables = $wgMemc->get( $this->mCacheKey );
820 wfProfileOut( __METHOD__ . '-cache' );
822 if ( !$this->mTables
823 || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
824 wfProfileIn( __METHOD__ . '-recache' );
825 // not in cache, or we need a fresh reload.
826 // We will first load the default tables
827 // then update them using things in MediaWiki:Conversiontable/*
828 $this->loadDefaultTables();
829 foreach ( $this->mVariants as $var ) {
830 $cached = $this->parseCachedTable( $var );
831 $this->mTables[$var]->mergeArray( $cached );
834 $this->postLoadTables();
835 $this->mTables[self::CACHE_VERSION_KEY] = true;
837 $wgMemc->set( $this->mCacheKey, $this->mTables, 43200 );
838 wfProfileOut( __METHOD__ . '-recache' );
840 wfProfileOut( __METHOD__ );
844 * Hook for post processing after conversion tables are loaded.
846 function postLoadTables() { }
849 * Reload the conversion tables.
851 * @private
853 function reloadTables() {
854 if ( $this->mTables ) {
855 unset( $this->mTables );
857 $this->mTablesLoaded = false;
858 $this->loadTables( false );
862 * Parse the conversion table stored in the cache.
864 * The tables should be in blocks of the following form:
865 * -{
866 * word => word ;
867 * word => word ;
868 * ...
869 * }-
871 * To make the tables more manageable, subpages are allowed
872 * and will be parsed recursively if $recursive == true.
874 * @param $code String: language code
875 * @param $subpage String: subpage name
876 * @param $recursive Boolean: parse subpages recursively? Defaults to true.
878 * @return array
880 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
881 static $parsed = array();
883 $key = 'Conversiontable/' . $code;
884 if ( $subpage ) {
885 $key .= '/' . $subpage;
887 if ( array_key_exists( $key, $parsed ) ) {
888 return array();
891 if ( strpos( $code, '/' ) === false ) {
892 $txt = MessageCache::singleton()->get( 'Conversiontable', true, $code );
893 if ( $txt === false ) {
894 # @todo FIXME: This method doesn't seem to be expecting
895 # this possible outcome...
896 $txt = '&lt;Conversiontable&gt;';
898 } else {
899 $title = Title::makeTitleSafe(
900 NS_MEDIAWIKI,
901 "Conversiontable/$code"
903 if ( $title && $title->exists() ) {
904 $article = new Article( $title );
905 $txt = $article->getContents();
906 } else {
907 $txt = '';
911 // get all subpage links of the form
912 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
913 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
914 ':Conversiontable';
915 $subs = StringUtils::explode( '[[', $txt );
916 $sublinks = array();
917 foreach ( $subs as $sub ) {
918 $link = explode( ']]', $sub, 2 );
919 if ( count( $link ) != 2 ) {
920 continue;
922 $b = explode( '|', $link[0], 2 );
923 $b = explode( '/', trim( $b[0] ), 3 );
924 if ( count( $b ) == 3 ) {
925 $sublink = $b[2];
926 } else {
927 $sublink = '';
930 if ( $b[0] == $linkhead && $b[1] == $code ) {
931 $sublinks[] = $sublink;
935 // parse the mappings in this page
936 $blocks = StringUtils::explode( '-{', $txt );
937 $ret = array();
938 $first = true;
939 foreach ( $blocks as $block ) {
940 if ( $first ) {
941 // Skip the part before the first -{
942 $first = false;
943 continue;
945 $mappings = explode( '}-', $block, 2 );
946 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
947 $mappings[0] );
948 $table = StringUtils::explode( ';', $stripped );
949 foreach ( $table as $t ) {
950 $m = explode( '=>', $t, 3 );
951 if ( count( $m ) != 2 ) {
952 continue;
954 // trim any trailling comments starting with '//'
955 $tt = explode( '//', $m[1], 2 );
956 $ret[trim( $m[0] )] = trim( $tt[0] );
959 $parsed[$key] = true;
961 // recursively parse the subpages
962 if ( $recursive ) {
963 foreach ( $sublinks as $link ) {
964 $s = $this->parseCachedTable( $code, $link, $recursive );
965 $ret = array_merge( $ret, $s );
969 if ( $this->mUcfirst ) {
970 foreach ( $ret as $k => $v ) {
971 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
974 return $ret;
978 * Enclose a string with the "no conversion" tag. This is used by
979 * various functions in the Parser.
981 * @param $text String: text to be tagged for no conversion
982 * @param $noParse Boolean: unused
983 * @return String: the tagged text
985 public function markNoConversion( $text, $noParse = false ) {
986 # don't mark if already marked
987 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
988 return $text;
991 $ret = "-{R|$text}-";
992 return $ret;
996 * Convert the sorting key for category links. This should make different
997 * keys that are variants of each other map to the same key.
999 * @param $key string
1001 * @return string
1003 function convertCategoryKey( $key ) {
1004 return $key;
1008 * Hook to refresh the cache of conversion tables when
1009 * MediaWiki:Conversiontable* is updated.
1010 * @private
1012 * @param $article Article object
1013 * @param $user Object: User object for the current user
1014 * @param $text String: article text (?)
1015 * @param $summary String: edit summary of the edit
1016 * @param $isMinor Boolean: was the edit marked as minor?
1017 * @param $isWatch Boolean: did the user watch this page or not?
1018 * @param $section Unused
1019 * @param $flags Bitfield
1020 * @param $revision Object: new Revision object or null
1021 * @return Boolean: true
1023 function OnArticleSaveComplete( $article, $user, $text, $summary, $isMinor,
1024 $isWatch, $section, $flags, $revision ) {
1025 $titleobj = $article->getTitle();
1026 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
1027 $title = $titleobj->getDBkey();
1028 $t = explode( '/', $title, 3 );
1029 $c = count( $t );
1030 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1031 if ( $this->validateVariant( $t[1] ) ) {
1032 $this->reloadTables();
1036 return true;
1040 * Armour rendered math against conversion.
1041 * Escape special chars in parsed math text. (in most cases are img elements)
1043 * @param $text String: text to armour against conversion
1044 * @return String: armoured text where { and } have been converted to
1045 * &#123; and &#125;
1047 public function armourMath( $text ) {
1048 // convert '-{' and '}-' to '-&#123;' and '&#125;-' to prevent
1049 // any unwanted markup appearing in the math image tag.
1050 $text = strtr( $text, array( '-{' => '-&#123;', '}-' => '&#125;-' ) );
1051 return $text;
1055 * Get the cached separator pattern for ConverterRule::parseRules()
1057 function getVarSeparatorPattern() {
1058 if ( is_null( $this->mVarSeparatorPattern ) ) {
1059 // varsep_pattern for preg_split:
1060 // text should be splited by ";" only if a valid variant
1061 // name exist after the markup, for example:
1062 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1063 // <span style="font-size:120%;">yyy</span>;}-
1064 // we should split it as:
1065 // array(
1066 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1067 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1068 // [2] => ''
1069 // )
1070 $pat = '/;\s*(?=';
1071 foreach ( $this->mVariants as $variant ) {
1072 // zh-hans:xxx;zh-hant:yyy
1073 $pat .= $variant . '\s*:|';
1074 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1075 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1077 $pat .= '\s*$)/';
1078 $this->mVarSeparatorPattern = $pat;
1080 return $this->mVarSeparatorPattern;
1085 * Parser for rules of language conversion , parse rules in -{ }- tag.
1086 * @ingroup Language
1087 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1089 class ConverterRule {
1090 var $mText; // original text in -{text}-
1091 var $mConverter; // LanguageConverter object
1092 var $mManualCodeError = '<strong class="error">code error!</strong>';
1093 var $mRuleDisplay = '';
1094 var $mRuleTitle = false;
1095 var $mRules = '';// string : the text of the rules
1096 var $mRulesAction = 'none';
1097 var $mFlags = array();
1098 var $mVariantFlags = array();
1099 var $mConvTable = array();
1100 var $mBidtable = array();// array of the translation in each variant
1101 var $mUnidtable = array();// array of the translation in each variant
1104 * Constructor
1106 * @param $text String: the text between -{ and }-
1107 * @param $converter LanguageConverter object
1109 public function __construct( $text, $converter ) {
1110 $this->mText = $text;
1111 $this->mConverter = $converter;
1115 * Check if variants array in convert array.
1117 * @param $variants Array or string: variant language code
1118 * @return String: translated text
1120 public function getTextInBidtable( $variants ) {
1121 $variants = (array)$variants;
1122 if ( !$variants ) {
1123 return false;
1125 foreach ( $variants as $variant ) {
1126 if ( isset( $this->mBidtable[$variant] ) ) {
1127 return $this->mBidtable[$variant];
1130 return false;
1134 * Parse flags with syntax -{FLAG| ... }-
1135 * @private
1137 function parseFlags() {
1138 $text = $this->mText;
1139 $flags = array();
1140 $variantFlags = array();
1142 $sepPos = strpos( $text, '|' );
1143 if ( $sepPos !== false ) {
1144 $validFlags = $this->mConverter->mFlags;
1145 $f = StringUtils::explode( ';', substr( $text, 0, $sepPos ) );
1146 foreach ( $f as $ff ) {
1147 $ff = trim( $ff );
1148 if ( isset( $validFlags[$ff] ) ) {
1149 $flags[$validFlags[$ff]] = true;
1152 $text = strval( substr( $text, $sepPos + 1 ) );
1155 if ( !$flags ) {
1156 $flags['S'] = true;
1157 } elseif ( isset( $flags['R'] ) ) {
1158 $flags = array( 'R' => true );// remove other flags
1159 } elseif ( isset( $flags['N'] ) ) {
1160 $flags = array( 'N' => true );// remove other flags
1161 } elseif ( isset( $flags['-'] ) ) {
1162 $flags = array( '-' => true );// remove other flags
1163 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1164 $flags['H'] = true;
1165 } elseif ( isset( $flags['H'] ) ) {
1166 // replace A flag, and remove other flags except T
1167 $temp = array( '+' => true, 'H' => true );
1168 if ( isset( $flags['T'] ) ) {
1169 $temp['T'] = true;
1171 if ( isset( $flags['D'] ) ) {
1172 $temp['D'] = true;
1174 $flags = $temp;
1175 } else {
1176 if ( isset( $flags['A'] ) ) {
1177 $flags['+'] = true;
1178 $flags['S'] = true;
1180 if ( isset( $flags['D'] ) ) {
1181 unset( $flags['S'] );
1183 // try to find flags like "zh-hans", "zh-hant"
1184 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1185 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter->mVariants );
1186 if ( $variantFlags ) {
1187 $variantFlags = array_flip( $variantFlags );
1188 $flags = array();
1191 $this->mVariantFlags = $variantFlags;
1192 $this->mRules = $text;
1193 $this->mFlags = $flags;
1197 * Generate conversion table.
1198 * @private
1200 function parseRules() {
1201 $rules = $this->mRules;
1202 $bidtable = array();
1203 $unidtable = array();
1204 $variants = $this->mConverter->mVariants;
1205 $varsep_pattern = $this->mConverter->getVarSeparatorPattern();
1207 $choice = preg_split( $varsep_pattern, $rules );
1209 foreach ( $choice as $c ) {
1210 $v = explode( ':', $c, 2 );
1211 if ( count( $v ) != 2 ) {
1212 // syntax error, skip
1213 continue;
1215 $to = trim( $v[1] );
1216 $v = trim( $v[0] );
1217 $u = explode( '=>', $v, 2 );
1218 // if $to is empty, strtr() could return a wrong result
1219 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1220 $bidtable[$v] = $to;
1221 } elseif ( count( $u ) == 2 ) {
1222 $from = trim( $u[0] );
1223 $v = trim( $u[1] );
1224 if ( array_key_exists( $v, $unidtable )
1225 && !is_array( $unidtable[$v] )
1226 && $to
1227 && in_array( $v, $variants ) ) {
1228 $unidtable[$v] = array( $from => $to );
1229 } elseif ( $to && in_array( $v, $variants ) ) {
1230 $unidtable[$v][$from] = $to;
1233 // syntax error, pass
1234 if ( !isset( $this->mConverter->mVariantNames[$v] ) ) {
1235 $bidtable = array();
1236 $unidtable = array();
1237 break;
1240 $this->mBidtable = $bidtable;
1241 $this->mUnidtable = $unidtable;
1245 * @private
1247 * @return string
1249 function getRulesDesc() {
1250 $codesep = $this->mConverter->mDescCodeSep;
1251 $varsep = $this->mConverter->mDescVarSep;
1252 $text = '';
1253 foreach ( $this->mBidtable as $k => $v ) {
1254 $text .= $this->mConverter->mVariantNames[$k] . "$codesep$v$varsep";
1256 foreach ( $this->mUnidtable as $k => $a ) {
1257 foreach ( $a as $from => $to ) {
1258 $text .= $from . '⇒' . $this->mConverter->mVariantNames[$k] .
1259 "$codesep$to$varsep";
1262 return $text;
1266 * Parse rules conversion.
1267 * @private
1269 * @param $variant
1271 * @return string
1273 function getRuleConvertedStr( $variant ) {
1274 $bidtable = $this->mBidtable;
1275 $unidtable = $this->mUnidtable;
1277 if ( count( $bidtable ) + count( $unidtable ) == 0 ) {
1278 return $this->mRules;
1279 } else {
1280 // display current variant in bidirectional array
1281 $disp = $this->getTextInBidtable( $variant );
1282 // or display current variant in fallbacks
1283 if ( !$disp ) {
1284 $disp = $this->getTextInBidtable(
1285 $this->mConverter->getVariantFallbacks( $variant ) );
1287 // or display current variant in unidirectional array
1288 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1289 $disp = array_values( $unidtable[$variant] );
1290 $disp = $disp[0];
1292 // or display frist text under disable manual convert
1293 if ( !$disp
1294 && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
1295 if ( count( $bidtable ) > 0 ) {
1296 $disp = array_values( $bidtable );
1297 $disp = $disp[0];
1298 } else {
1299 $disp = array_values( $unidtable );
1300 $disp = array_values( $disp[0] );
1301 $disp = $disp[0];
1304 return $disp;
1309 * Generate conversion table for all text.
1310 * @private
1312 function generateConvTable() {
1313 // Special case optimisation
1314 if ( !$this->mBidtable && !$this->mUnidtable ) {
1315 $this->mConvTable = array();
1316 return;
1319 $bidtable = $this->mBidtable;
1320 $unidtable = $this->mUnidtable;
1321 $manLevel = $this->mConverter->mManualLevel;
1323 $vmarked = array();
1324 foreach ( $this->mConverter->mVariants as $v ) {
1325 /* for bidirectional array
1326 fill in the missing variants, if any,
1327 with fallbacks */
1328 if ( !isset( $bidtable[$v] ) ) {
1329 $variantFallbacks =
1330 $this->mConverter->getVariantFallbacks( $v );
1331 $vf = $this->getTextInBidtable( $variantFallbacks );
1332 if ( $vf ) {
1333 $bidtable[$v] = $vf;
1337 if ( isset( $bidtable[$v] ) ) {
1338 foreach ( $vmarked as $vo ) {
1339 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1340 // or -{H|zh:WordZh;zh-tw:WordTw}-
1341 // or -{-|zh:WordZh;zh-tw:WordTw}-
1342 // to introduce a custom mapping between
1343 // words WordZh and WordTw in the whole text
1344 if ( $manLevel[$v] == 'bidirectional' ) {
1345 $this->mConvTable[$v][$bidtable[$vo]] = $bidtable[$v];
1347 if ( $manLevel[$vo] == 'bidirectional' ) {
1348 $this->mConvTable[$vo][$bidtable[$v]] = $bidtable[$vo];
1351 $vmarked[] = $v;
1353 /* for unidirectional array fill to convert tables */
1354 if ( ( $manLevel[$v] == 'bidirectional' || $manLevel[$v] == 'unidirectional' )
1355 && isset( $unidtable[$v] ) )
1357 if ( isset( $this->mConvTable[$v] ) ) {
1358 $this->mConvTable[$v] = array_merge( $this->mConvTable[$v], $unidtable[$v] );
1359 } else {
1360 $this->mConvTable[$v] = $unidtable[$v];
1367 * Parse rules and flags.
1368 * @param $variant String: variant language code
1370 public function parse( $variant = null ) {
1371 if ( !$variant ) {
1372 $variant = $this->mConverter->getPreferredVariant();
1375 $this->parseFlags();
1376 $flags = $this->mFlags;
1378 // convert to specified variant
1379 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1380 if ( $this->mVariantFlags ) {
1381 // check if current variant in flags
1382 if ( isset( $this->mVariantFlags[$variant] ) ) {
1383 // then convert <text to convert> to current language
1384 $this->mRules = $this->mConverter->autoConvert( $this->mRules,
1385 $variant );
1386 } else { // if current variant no in flags,
1387 // then we check its fallback variants.
1388 $variantFallbacks =
1389 $this->mConverter->getVariantFallbacks( $variant );
1390 foreach ( $variantFallbacks as $variantFallback ) {
1391 // if current variant's fallback exist in flags
1392 if ( isset( $this->mVariantFlags[$variantFallback] ) ) {
1393 // then convert <text to convert> to fallback language
1394 $this->mRules =
1395 $this->mConverter->autoConvert( $this->mRules,
1396 $variantFallback );
1397 break;
1401 $this->mFlags = $flags = array( 'R' => true );
1404 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1405 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1406 $this->mRules = str_replace( '=&gt;', '=>', $this->mRules );
1407 $this->parseRules();
1409 $rules = $this->mRules;
1411 if ( !$this->mBidtable && !$this->mUnidtable ) {
1412 if ( isset( $flags['+'] ) || isset( $flags['-'] ) ) {
1413 // fill all variants if text in -{A/H/-|text} without rules
1414 foreach ( $this->mConverter->mVariants as $v ) {
1415 $this->mBidtable[$v] = $rules;
1417 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1418 $this->mFlags = $flags = array( 'R' => true );
1422 $this->mRuleDisplay = false;
1423 foreach ( $flags as $flag => $unused ) {
1424 switch ( $flag ) {
1425 case 'R':
1426 // if we don't do content convert, still strip the -{}- tags
1427 $this->mRuleDisplay = $rules;
1428 break;
1429 case 'N':
1430 // process N flag: output current variant name
1431 $ruleVar = trim( $rules );
1432 if ( isset( $this->mConverter->mVariantNames[$ruleVar] ) ) {
1433 $this->mRuleDisplay = $this->mConverter->mVariantNames[$ruleVar];
1434 } else {
1435 $this->mRuleDisplay = '';
1437 break;
1438 case 'D':
1439 // process D flag: output rules description
1440 $this->mRuleDisplay = $this->getRulesDesc();
1441 break;
1442 case 'H':
1443 // process H,- flag or T only: output nothing
1444 $this->mRuleDisplay = '';
1445 break;
1446 case '-':
1447 $this->mRulesAction = 'remove';
1448 $this->mRuleDisplay = '';
1449 break;
1450 case '+':
1451 $this->mRulesAction = 'add';
1452 $this->mRuleDisplay = '';
1453 break;
1454 case 'S':
1455 $this->mRuleDisplay = $this->getRuleConvertedStr( $variant );
1456 break;
1457 case 'T':
1458 $this->mRuleTitle = $this->getRuleConvertedStr( $variant );
1459 $this->mRuleDisplay = '';
1460 break;
1461 default:
1462 // ignore unknown flags (but see error case below)
1465 if ( $this->mRuleDisplay === false ) {
1466 $this->mRuleDisplay = $this->mManualCodeError;
1469 $this->generateConvTable();
1473 * @todo FIXME: code this function :)
1475 public function hasRules() {
1476 // TODO:
1480 * Get display text on markup -{...}-
1481 * @return string
1483 public function getDisplay() {
1484 return $this->mRuleDisplay;
1488 * Get converted title.
1489 * @return string
1491 public function getTitle() {
1492 return $this->mRuleTitle;
1496 * Return how deal with conversion rules.
1497 * @return string
1499 public function getRulesAction() {
1500 return $this->mRulesAction;
1504 * Get conversion table. (bidirectional and unidirectional
1505 * conversion table)
1506 * @return array
1508 public function getConvTable() {
1509 return $this->mConvTable;
1513 * Get conversion rules string.
1514 * @return string
1516 public function getRules() {
1517 return $this->mRules;
1521 * Get conversion flags.
1522 * @return array
1524 public function getFlags() {
1525 return $this->mFlags;