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
25 * Base class for language conversion.
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
{
34 * languages supporting variants
38 static public $languagesWithVariants = array(
50 public $mMainLanguageCode;
51 public $mVariants, $mVariantFallbacks, $mVariantNames;
52 public $mTablesLoaded = false;
54 // 'bidirectional' 'unidirectional' 'disable' for each variant
58 * @var String: memcached key name
64 public $mDescCodeSep = ':', $mDescVarSep = ';';
65 public $mUcfirst = false;
66 public $mConvRuleTitle = false;
69 public $mHeaderVariant;
70 public $mMaxDepth = 10;
71 public $mVarSeparatorPattern;
73 const CACHE_VERSION_KEY
= 'VERSION 7';
78 * @param $langobj Language: the Language Object
79 * @param $maincode String: the main language code of this language
80 * @param $variants Array: the supported variants of this language
81 * @param $variantfallbacks Array: the fallback language of each variant
82 * @param $flags Array: defining the custom strings that maps to the flags
83 * @param $manualLevel Array: limit for supported variants
85 public function __construct( $langobj, $maincode, $variants = array(),
86 $variantfallbacks = array(), $flags = array(),
87 $manualLevel = array() ) {
88 global $wgDisabledVariants;
89 $this->mLangObj
= $langobj;
90 $this->mMainLanguageCode
= $maincode;
91 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
92 $this->mVariantFallbacks
= $variantfallbacks;
93 $this->mVariantNames
= Language
::fetchLanguageNames();
94 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
95 $defaultflags = array(
96 // 'S' show converted text
97 // '+' add rules for alltext
98 // 'E' the gave flags is error
99 // these flags above are reserved for program
100 'A' => 'A', // add rule for convert code (all text convert)
101 'T' => 'T', // title convert
102 'R' => 'R', // raw content
103 'D' => 'D', // convert description (subclass implement)
104 '-' => '-', // remove convert (not implement)
105 'H' => 'H', // add rule for convert code (but no display in placed code)
106 'N' => 'N' // current variant name
108 $this->mFlags
= array_merge( $defaultflags, $flags );
109 foreach ( $this->mVariants
as $v ) {
110 if ( array_key_exists( $v, $manualLevel ) ) {
111 $this->mManualLevel
[$v] = $manualLevel[$v];
113 $this->mManualLevel
[$v] = 'bidirectional';
115 $this->mFlags
[$v] = $v;
120 * Get all valid variants.
121 * Call this instead of using $this->mVariants directly.
123 * @return Array: contains all valid variants
125 public function getVariants() {
126 return $this->mVariants
;
130 * In case some variant is not defined in the markup, we need
131 * to have some fallback. For example, in zh, normally people
132 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
133 * when zh-sg is preferred but not defined, we will pick zh-hans
134 * in this case. Right now this is only used by zh.
136 * @param $variant String: the language code of the variant
137 * @return String|array: The code of the fallback language or the
138 * main code if there is no fallback
140 public function getVariantFallbacks( $variant ) {
141 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
142 return $this->mVariantFallbacks
[$variant];
144 return $this->mMainLanguageCode
;
148 * Get the title produced by the conversion rule.
149 * @return String: The converted title text
151 public function getConvRuleTitle() {
152 return $this->mConvRuleTitle
;
156 * Get preferred language variant.
157 * @return String: the preferred language code
159 public function getPreferredVariant() {
160 global $wgDefaultLanguageVariant, $wgUser;
162 $req = $this->getURLVariant();
164 if ( $wgUser->isLoggedIn() && !$req ) {
165 $req = $this->getUserVariant();
167 $req = $this->getHeaderVariant();
170 if ( $wgDefaultLanguageVariant && !$req ) {
171 $req = $this->validateVariant( $wgDefaultLanguageVariant );
174 // This function, unlike the other get*Variant functions, is
175 // not memoized (i.e. there return value is not cached) since
176 // new information might appear during processing after this
178 if ( $this->validateVariant( $req ) ) {
181 return $this->mMainLanguageCode
;
185 * Get default variant.
186 * This function would not be affected by user's settings
187 * @return String: the default variant code
189 public function getDefaultVariant() {
190 global $wgDefaultLanguageVariant;
192 $req = $this->getURLVariant();
195 $req = $this->getHeaderVariant();
198 if ( $wgDefaultLanguageVariant && !$req ) {
199 $req = $this->validateVariant( $wgDefaultLanguageVariant );
205 return $this->mMainLanguageCode
;
209 * Validate the variant
210 * @param $variant String: the variant to validate
211 * @return Mixed: returns the variant if it is valid, null otherwise
213 public function validateVariant( $variant = null ) {
214 if ( $variant !== null && in_array( $variant, $this->mVariants
) ) {
221 * Get the variant specified in the URL
223 * @return Mixed: variant if one found, false otherwise.
225 public function getURLVariant() {
228 if ( $this->mURLVariant
) {
229 return $this->mURLVariant
;
232 // see if the preference is set in the request
233 $ret = $wgRequest->getText( 'variant' );
236 $ret = $wgRequest->getVal( 'uselang' );
239 return $this->mURLVariant
= $this->validateVariant( $ret );
243 * Determine if the user has a variant set.
245 * @return Mixed: variant if one found, false otherwise.
247 protected function getUserVariant() {
248 global $wgUser, $wgContLang;
250 // memoizing this function wreaks havoc on parserTest.php
252 if ( $this->mUserVariant ) {
253 return $this->mUserVariant;
257 // Get language variant preference from logged in users
258 // Don't call this on stub objects because that causes infinite
259 // recursion during initialisation
260 if ( $wgUser->isLoggedIn() ) {
261 if ( $this->mMainLanguageCode
== $wgContLang->getCode() ) {
262 $ret = $wgUser->getOption( 'variant' );
264 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode
);
267 // figure out user lang without constructing wgLang to avoid
268 // infinite recursion
269 $ret = $wgUser->getOption( 'language' );
272 return $this->mUserVariant
= $this->validateVariant( $ret );
276 * Determine the language variant from the Accept-Language header.
278 * @return Mixed: variant if one found, false otherwise.
280 protected function getHeaderVariant() {
283 if ( $this->mHeaderVariant
) {
284 return $this->mHeaderVariant
;
287 // see if some supported language variant is set in the
289 $languages = array_keys( $wgRequest->getAcceptLang() );
290 if ( empty( $languages ) ) {
294 $fallbackLanguages = array();
295 foreach ( $languages as $language ) {
296 $this->mHeaderVariant
= $this->validateVariant( $language );
297 if ( $this->mHeaderVariant
) {
301 // To see if there are fallbacks of current language.
302 // We record these fallback variants, and process
304 $fallbacks = $this->getVariantFallbacks( $language );
305 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
306 $fallbackLanguages[] = $fallbacks;
307 } elseif ( is_array( $fallbacks ) ) {
309 array_merge( $fallbackLanguages, $fallbacks );
313 if ( !$this->mHeaderVariant
) {
314 // process fallback languages now
315 $fallback_languages = array_unique( $fallbackLanguages );
316 foreach ( $fallback_languages as $language ) {
317 $this->mHeaderVariant
= $this->validateVariant( $language );
318 if ( $this->mHeaderVariant
) {
324 return $this->mHeaderVariant
;
328 * Dictionary-based conversion.
329 * This function would not parse the conversion rules.
330 * If you want to parse rules, try to use convert() or
333 * @param $text String the text to be converted
334 * @param $toVariant bool|string the target language code
335 * @return String the converted text
337 public function autoConvert( $text, $toVariant = false ) {
338 wfProfileIn( __METHOD__
);
343 $toVariant = $this->getPreferredVariant();
345 wfProfileOut( __METHOD__
);
350 if ( $this->guessVariant( $text, $toVariant ) ) {
351 wfProfileOut( __METHOD__
);
355 /* we convert everything except:
356 1. HTML markups (anything between < and >)
358 3. placeholders created by the parser
361 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
362 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
367 // this one is needed when the text is inside an HTML markup
368 $htmlfix = '|<[^>]+$|^[^<>]*>';
370 // disable convert to variants between <code> tags
371 $codefix = '<code>.+?<\/code>|';
372 // disable conversion of <script> tags
373 $scriptfix = '<script.*?>.*?<\/script>|';
374 // disable conversion of <pre> tags
375 $prefix = '<pre.*?>.*?<\/pre>|';
377 $reg = '/' . $codefix . $scriptfix . $prefix .
378 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
383 // Guard against delimiter nulls in the input
384 $text = str_replace( "\000", '', $text );
386 $markupMatches = null;
387 $elementMatches = null;
388 while ( $startPos < strlen( $text ) ) {
389 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
390 $elementPos = $markupMatches[0][1];
391 $element = $markupMatches[0][0];
393 $elementPos = strlen( $text );
397 // Queue the part before the markup for translation in a batch
398 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
400 // Advance to the next position
401 $startPos = $elementPos +
strlen( $element );
403 // Translate any alt or title attributes inside the matched element
405 && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element, $elementMatches )
407 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
409 foreach ( array( 'title', 'alt' ) as $attrName ) {
410 if ( !isset( $attrs[$attrName] ) ) {
413 $attr = $attrs[$attrName];
414 // Don't convert URLs
415 if ( !strpos( $attr, '://' ) ) {
416 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
419 // Remove HTML tags to avoid disrupting the layout
420 $attr = preg_replace( '/<[^>]+>/', '', $attr );
421 if ( $attr !== $attrs[$attrName] ) {
422 $attrs[$attrName] = $attr;
427 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
431 $literalBlob .= $element . "\000";
434 // Do the main translation batch
435 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
437 // Put the output back together
438 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
439 $literalIter = StringUtils
::explode( "\000", $literalBlob );
441 while ( $translatedIter->valid() && $literalIter->valid() ) {
442 $output .= $translatedIter->current();
443 $output .= $literalIter->current();
444 $translatedIter->next();
445 $literalIter->next();
448 wfProfileOut( __METHOD__
);
453 * Translate a string to a variant.
454 * Doesn't parse rules or do any of that other stuff, for that use
455 * convert() or convertTo().
457 * @param $text String: text to convert
458 * @param $variant String: variant language code
459 * @return String: translated text
461 public function translate( $text, $variant ) {
462 wfProfileIn( __METHOD__
);
463 // If $text is empty or only includes spaces, do nothing
464 // Otherwise translate it
465 if ( trim( $text ) ) {
467 $text = $this->mTables
[$variant]->replace( $text );
469 wfProfileOut( __METHOD__
);
474 * Call translate() to convert text to all valid variants.
476 * @param $text String: the text to be converted
477 * @return Array: variant => converted text
479 public function autoConvertToAllVariants( $text ) {
480 wfProfileIn( __METHOD__
);
484 foreach ( $this->mVariants
as $variant ) {
485 $ret[$variant] = $this->translate( $text, $variant );
488 wfProfileOut( __METHOD__
);
493 * Convert link text to all valid variants.
494 * In the first, this function only convert text outside the
495 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
496 * titles, the text will get all converted always.
497 * So I removed this feature and deprecated the function.
499 * @param $text String: the text to be converted
500 * @return Array: variant => converted text
501 * @deprecated since 1.17 Use autoConvertToAllVariants() instead
503 public function convertLinkToAllVariants( $text ) {
504 return $this->autoConvertToAllVariants( $text );
508 * Apply manual conversion rules.
510 * @param $convRule ConverterRule Object of ConverterRule
512 protected function applyManualConv( $convRule ) {
513 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
515 // Bug 24072: $mConvRuleTitle was overwritten by other manual
516 // rule(s) not for title, this breaks the title conversion.
517 $newConvRuleTitle = $convRule->getTitle();
518 if ( $newConvRuleTitle ) {
519 // So I add an empty check for getTitle()
520 $this->mConvRuleTitle
= $newConvRuleTitle;
523 // merge/remove manual conversion rules to/from global table
524 $convTable = $convRule->getConvTable();
525 $action = $convRule->getRulesAction();
526 foreach ( $convTable as $variant => $pair ) {
527 if ( !$this->validateVariant( $variant ) ) {
531 if ( $action == 'add' ) {
532 foreach ( $pair as $from => $to ) {
533 // to ensure that $from and $to not be left blank
534 // so $this->translate() could always return a string
535 if ( $from ||
$to ) {
536 // more efficient than array_merge(), about 2.5 times.
537 $this->mTables
[$variant]->setPair( $from, $to );
540 } elseif ( $action == 'remove' ) {
541 $this->mTables
[$variant]->removeArray( $pair );
547 * Auto convert a Title object to a readable string in the
550 * @param $title Title a object of Title
551 * @return String: converted title text
553 public function convertTitle( $title ) {
554 $variant = $this->getPreferredVariant();
555 $index = $title->getNamespace();
556 if ( $index !== NS_MAIN
) {
557 $text = $this->convertNamespace( $index, $variant ) . ':';
561 $text .= $this->translate( $title->getText(), $variant );
566 * Get the namespace display name in the preferred variant.
568 * @param $index int namespace id
569 * @param $variant string|null variant code or null for preferred variant
570 * @return String: namespace name for display
572 public function convertNamespace( $index, $variant = null ) {
573 if ( $variant === null ) {
574 $variant = $this->getPreferredVariant();
576 if ( $index === NS_MAIN
) {
579 // First check if a message gives a converted name in the target variant.
580 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
581 if ( $nsConvMsg->exists() ) {
582 return $nsConvMsg->plain();
584 // Then check if a message gives a converted name in content language
585 // which needs extra translation to the target variant.
586 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
587 if ( $nsConvMsg->exists() ) {
588 return $this->translate( $nsConvMsg->plain(), $variant );
590 // No message exists, retrieve it from the target variant's namespace names.
591 $langObj = $this->mLangObj
->factory( $variant );
592 return $langObj->getFormattedNsText( $index );
597 * Convert text to different variants of a language. The automatic
598 * conversion is done in autoConvert(). Here we parse the text
599 * marked with -{}-, which specifies special conversions of the
600 * text that can not be accomplished in autoConvert().
602 * Syntax of the markup:
603 * -{code1:text1;code2:text2;...}- or
604 * -{flags|code1:text1;code2:text2;...}- or
605 * -{text}- in which case no conversion should take place for text
607 * @param $text String: text to be converted
608 * @return String: converted text
610 public function convert( $text ) {
611 $variant = $this->getPreferredVariant();
612 return $this->convertTo( $text, $variant );
616 * Same as convert() except a extra parameter to custom variant.
618 * @param $text String: text to be converted
619 * @param $variant String: the target variant code
620 * @return String: converted text
622 public function convertTo( $text, $variant ) {
623 global $wgDisableLangConversion;
624 if ( $wgDisableLangConversion ) {
627 // Reset converter state for a new converter run.
628 $this->mConvRuleTitle
= false;
629 return $this->recursiveConvertTopLevel( $text, $variant );
633 * Recursively convert text on the outside. Allow to use nested
634 * markups to custom rules.
636 * @param $text String: text to be converted
637 * @param $variant String: the target variant code
638 * @param $depth Integer: depth of recursion
639 * @return String: converted text
641 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
644 $length = strlen( $text );
645 $shouldConvert = !$this->guessVariant( $text, $variant );
647 while ( $startPos < $length ) {
648 $pos = strpos( $text, '-{', $startPos );
650 if ( $pos === false ) {
651 // No more markup, append final segment
652 $fragment = substr( $text, $startPos );
653 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
658 // Append initial segment
659 $fragment = substr( $text, $startPos, $pos - $startPos );
660 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
665 // Do recursive conversion
666 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
673 * Recursively convert text on the inside.
675 * @param $text String: text to be converted
676 * @param $variant String: the target variant code
677 * @param $startPos int
678 * @param $depth Integer: depth of recursion
680 * @throws MWException
681 * @return String: converted text
683 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
684 // Quick sanity check (no function calls)
685 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
686 throw new MWException( __METHOD__
. ': invalid input string' );
691 $warningDone = false;
692 $length = strlen( $text );
694 while ( $startPos < $length ) {
696 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
706 // Append initial segment
707 $inner .= substr( $text, $startPos, $pos - $startPos );
715 if ( $depth >= $this->mMaxDepth
) {
717 if ( !$warningDone ) {
718 $inner .= '<span class="error">' .
719 wfMessage( 'language-converter-depth-warning' )
720 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
727 // Recursively parse another rule
728 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
733 $rule = new ConverterRule( $inner, $this );
734 $rule->parse( $variant );
735 $this->applyManualConv( $rule );
736 return $rule->getDisplay();
738 throw new MWException( __METHOD__
. ': invalid regex match' );
743 if ( $startPos < $length ) {
744 $inner .= substr( $text, $startPos );
747 return '-{' . $this->autoConvert( $inner, $variant );
751 * If a language supports multiple variants, it is possible that
752 * non-existing link in one variant actually exists in another variant.
753 * This function tries to find it. See e.g. LanguageZh.php
755 * @param $link String: the name of the link
756 * @param $nt Mixed: the title object of the link
757 * @param $ignoreOtherCond Boolean: to disable other conditions when
758 * we need to transclude a template or update a category's link
759 * @return Null, the input parameters may be modified upon return
761 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
762 # If the article has already existed, there is no need to
763 # check it again, otherwise it may cause a fault.
764 if ( is_object( $nt ) && $nt->exists() ) {
768 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
770 $isredir = $wgRequest->getText( 'redirect', 'yes' );
771 $action = $wgRequest->getText( 'action' );
772 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
773 $disableLinkConversion = $wgDisableLangConversion
774 ||
$wgDisableTitleConversion;
775 $linkBatch = new LinkBatch();
779 if ( $disableLinkConversion ||
780 ( !$ignoreOtherCond &&
783 ||
$action == 'submit'
784 ||
$linkconvert == 'no'
785 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
789 if ( is_object( $nt ) ) {
790 $ns = $nt->getNamespace();
793 $variants = $this->autoConvertToAllVariants( $link );
794 if ( !$variants ) { // give up
800 foreach ( $variants as $v ) {
802 $varnt = Title
::newFromText( $v, $ns );
803 if ( !is_null( $varnt ) ) {
804 $linkBatch->addObj( $varnt );
810 // fetch all variants in single query
811 $linkBatch->execute();
813 foreach ( $titles as $varnt ) {
814 if ( $varnt->getArticleID() > 0 ) {
816 $link = $varnt->getText();
823 * Returns language specific hash options.
827 public function getExtraHashOptions() {
828 $variant = $this->getPreferredVariant();
829 return '!' . $variant;
833 * Guess if a text is written in a variant. This should be implemented in subclasses.
835 * @param string $text the text to be checked
836 * @param string $variant language code of the variant to be checked for
837 * @return bool true if $text appears to be written in $variant, false if not
839 * @author Nikola Smolenski <smolensk@eunet.rs>
842 public function guessVariant( $text, $variant ) {
847 * Load default conversion tables.
848 * This method must be implemented in derived class.
851 * @throws MWException
853 function loadDefaultTables() {
854 $name = get_class( $this );
855 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
859 * Load conversion tables either from the cache or the disk.
861 * @param $fromCache Boolean: load from memcached? Defaults to true.
863 function loadTables( $fromCache = true ) {
864 global $wgLangConvMemc;
866 if ( $this->mTablesLoaded
) {
870 wfProfileIn( __METHOD__
);
871 $this->mTablesLoaded
= true;
872 $this->mTables
= false;
874 wfProfileIn( __METHOD__
. '-cache' );
875 $this->mTables
= $wgLangConvMemc->get( $this->mCacheKey
);
876 wfProfileOut( __METHOD__
. '-cache' );
878 if ( !$this->mTables ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
879 wfProfileIn( __METHOD__
. '-recache' );
880 // not in cache, or we need a fresh reload.
881 // We will first load the default tables
882 // then update them using things in MediaWiki:Conversiontable/*
883 $this->loadDefaultTables();
884 foreach ( $this->mVariants
as $var ) {
885 $cached = $this->parseCachedTable( $var );
886 $this->mTables
[$var]->mergeArray( $cached );
889 $this->postLoadTables();
890 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
892 $wgLangConvMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
893 wfProfileOut( __METHOD__
. '-recache' );
895 wfProfileOut( __METHOD__
);
899 * Hook for post processing after conversion tables are loaded.
901 function postLoadTables() { }
904 * Reload the conversion tables.
908 function reloadTables() {
909 if ( $this->mTables
) {
910 unset( $this->mTables
);
912 $this->mTablesLoaded
= false;
913 $this->loadTables( false );
917 * Parse the conversion table stored in the cache.
919 * The tables should be in blocks of the following form:
926 * To make the tables more manageable, subpages are allowed
927 * and will be parsed recursively if $recursive == true.
929 * @param $code String: language code
930 * @param $subpage String: subpage name
931 * @param $recursive Boolean: parse subpages recursively? Defaults to true.
935 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
936 static $parsed = array();
938 $key = 'Conversiontable/' . $code;
940 $key .= '/' . $subpage;
942 if ( array_key_exists( $key, $parsed ) ) {
946 $parsed[$key] = true;
948 if ( $subpage === '' ) {
949 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
952 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
953 if ( $title && $title->exists() ) {
954 $revision = Revision
::newFromTitle( $title );
956 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
957 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
960 // @todo in the future, use a specialized content model, perhaps based on json!
965 # Nothing to parse if there's no text
966 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
970 // get all subpage links of the form
971 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
972 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
974 $subs = StringUtils
::explode( '[[', $txt );
976 foreach ( $subs as $sub ) {
977 $link = explode( ']]', $sub, 2 );
978 if ( count( $link ) != 2 ) {
981 $b = explode( '|', $link[0], 2 );
982 $b = explode( '/', trim( $b[0] ), 3 );
983 if ( count( $b ) == 3 ) {
989 if ( $b[0] == $linkhead && $b[1] == $code ) {
990 $sublinks[] = $sublink;
994 // parse the mappings in this page
995 $blocks = StringUtils
::explode( '-{', $txt );
998 foreach ( $blocks as $block ) {
1000 // Skip the part before the first -{
1004 $mappings = explode( '}-', $block, 2 );
1005 $stripped = str_replace( array( "'", '"', '*', '#' ), '', $mappings[0] );
1006 $table = StringUtils
::explode( ';', $stripped );
1007 foreach ( $table as $t ) {
1008 $m = explode( '=>', $t, 3 );
1009 if ( count( $m ) != 2 ) {
1012 // trim any trailling comments starting with '//'
1013 $tt = explode( '//', $m[1], 2 );
1014 $ret[trim( $m[0] )] = trim( $tt[0] );
1018 // recursively parse the subpages
1020 foreach ( $sublinks as $link ) {
1021 $s = $this->parseCachedTable( $code, $link, $recursive );
1022 $ret = array_merge( $ret, $s );
1026 if ( $this->mUcfirst
) {
1027 foreach ( $ret as $k => $v ) {
1028 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1035 * Enclose a string with the "no conversion" tag. This is used by
1036 * various functions in the Parser.
1038 * @param $text String: text to be tagged for no conversion
1039 * @param $noParse Boolean: unused
1040 * @return String: the tagged text
1042 public function markNoConversion( $text, $noParse = false ) {
1043 # don't mark if already marked
1044 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1048 $ret = "-{R|$text}-";
1053 * Convert the sorting key for category links. This should make different
1054 * keys that are variants of each other map to the same key.
1056 * @param $key string
1060 function convertCategoryKey( $key ) {
1065 * Hook to refresh the cache of conversion tables when
1066 * MediaWiki:Conversiontable* is updated.
1069 * @param $page WikiPage object
1070 * @param $user Object: User object for the current user
1071 * @param $content Content: new page content
1072 * @param $summary String: edit summary of the edit
1073 * @param $isMinor Boolean: was the edit marked as minor?
1074 * @param $isWatch Boolean: did the user watch this page or not?
1076 * @param $flags int Bitfield
1077 * @param $revision Object: new Revision object or null
1078 * @return Boolean: true
1080 function OnPageContentSaveComplete( $page, $user, $content, $summary, $isMinor,
1081 $isWatch, $section, $flags, $revision ) {
1082 $titleobj = $page->getTitle();
1083 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1084 $title = $titleobj->getDBkey();
1085 $t = explode( '/', $title, 3 );
1087 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1088 if ( $this->validateVariant( $t[1] ) ) {
1089 $this->reloadTables();
1097 * Armour rendered math against conversion.
1098 * Escape special chars in parsed math text. (in most cases are img elements)
1100 * @param $text String: text to armour against conversion
1101 * @return String: armoured text where { and } have been converted to
1103 * @deprecated since 1.22 is no longer used
1105 public function armourMath( $text ) {
1106 // convert '-{' and '}-' to '-{' and '}-' to prevent
1107 // any unwanted markup appearing in the math image tag.
1108 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
1113 * Get the cached separator pattern for ConverterRule::parseRules()
1115 function getVarSeparatorPattern() {
1116 if ( is_null( $this->mVarSeparatorPattern
) ) {
1117 // varsep_pattern for preg_split:
1118 // text should be splited by ";" only if a valid variant
1119 // name exist after the markup, for example:
1120 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1121 // <span style="font-size:120%;">yyy</span>;}-
1122 // we should split it as:
1124 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1125 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1129 foreach ( $this->mVariants
as $variant ) {
1130 // zh-hans:xxx;zh-hant:yyy
1131 $pat .= $variant . '\s*:|';
1132 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1133 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1136 $this->mVarSeparatorPattern
= $pat;
1138 return $this->mVarSeparatorPattern
;
1143 * Parser for rules of language conversion , parse rules in -{ }- tag.
1145 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1147 class ConverterRule
{
1148 public $mText; // original text in -{text}-
1149 public $mConverter; // LanguageConverter object
1150 public $mRuleDisplay = '';
1151 public $mRuleTitle = false;
1152 public $mRules = '';// string : the text of the rules
1153 public $mRulesAction = 'none';
1154 public $mFlags = array();
1155 public $mVariantFlags = array();
1156 public $mConvTable = array();
1157 public $mBidtable = array();// array of the translation in each variant
1158 public $mUnidtable = array();// array of the translation in each variant
1163 * @param $text String: the text between -{ and }-
1164 * @param $converter LanguageConverter object
1166 public function __construct( $text, $converter ) {
1167 $this->mText
= $text;
1168 $this->mConverter
= $converter;
1172 * Check if variants array in convert array.
1174 * @param $variants Array or string: variant language code
1175 * @return String: translated text
1177 public function getTextInBidtable( $variants ) {
1178 $variants = (array)$variants;
1182 foreach ( $variants as $variant ) {
1183 if ( isset( $this->mBidtable
[$variant] ) ) {
1184 return $this->mBidtable
[$variant];
1191 * Parse flags with syntax -{FLAG| ... }-
1194 function parseFlags() {
1195 $text = $this->mText
;
1197 $variantFlags = array();
1199 $sepPos = strpos( $text, '|' );
1200 if ( $sepPos !== false ) {
1201 $validFlags = $this->mConverter
->mFlags
;
1202 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1203 foreach ( $f as $ff ) {
1205 if ( isset( $validFlags[$ff] ) ) {
1206 $flags[$validFlags[$ff]] = true;
1209 $text = strval( substr( $text, $sepPos +
1 ) );
1214 } elseif ( isset( $flags['R'] ) ) {
1215 $flags = array( 'R' => true );// remove other flags
1216 } elseif ( isset( $flags['N'] ) ) {
1217 $flags = array( 'N' => true );// remove other flags
1218 } elseif ( isset( $flags['-'] ) ) {
1219 $flags = array( '-' => true );// remove other flags
1220 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1222 } elseif ( isset( $flags['H'] ) ) {
1223 // replace A flag, and remove other flags except T
1224 $temp = array( '+' => true, 'H' => true );
1225 if ( isset( $flags['T'] ) ) {
1228 if ( isset( $flags['D'] ) ) {
1233 if ( isset( $flags['A'] ) ) {
1237 if ( isset( $flags['D'] ) ) {
1238 unset( $flags['S'] );
1240 // try to find flags like "zh-hans", "zh-hant"
1241 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1242 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1243 if ( $variantFlags ) {
1244 $variantFlags = array_flip( $variantFlags );
1248 $this->mVariantFlags
= $variantFlags;
1249 $this->mRules
= $text;
1250 $this->mFlags
= $flags;
1254 * Generate conversion table.
1257 function parseRules() {
1258 $rules = $this->mRules
;
1259 $bidtable = array();
1260 $unidtable = array();
1261 $variants = $this->mConverter
->mVariants
;
1262 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1264 // Split according to $varsep_pattern, but ignore semicolons from HTML entities
1265 $rules = preg_replace( '/(&[#a-zA-Z0-9]+);/', "$1\x01", $rules );
1266 $choice = preg_split( $varsep_pattern, $rules );
1267 $choice = str_replace( "\x01", ';', $choice );
1269 foreach ( $choice as $c ) {
1270 $v = explode( ':', $c, 2 );
1271 if ( count( $v ) != 2 ) {
1272 // syntax error, skip
1275 $to = trim( $v[1] );
1277 $u = explode( '=>', $v, 2 );
1278 // if $to is empty, strtr() could return a wrong result
1279 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1280 $bidtable[$v] = $to;
1281 } elseif ( count( $u ) == 2 ) {
1282 $from = trim( $u[0] );
1284 if ( array_key_exists( $v, $unidtable )
1285 && !is_array( $unidtable[$v] )
1287 && in_array( $v, $variants ) ) {
1288 $unidtable[$v] = array( $from => $to );
1289 } elseif ( $to && in_array( $v, $variants ) ) {
1290 $unidtable[$v][$from] = $to;
1293 // syntax error, pass
1294 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1295 $bidtable = array();
1296 $unidtable = array();
1300 $this->mBidtable
= $bidtable;
1301 $this->mUnidtable
= $unidtable;
1309 function getRulesDesc() {
1310 $codesep = $this->mConverter
->mDescCodeSep
;
1311 $varsep = $this->mConverter
->mDescVarSep
;
1313 foreach ( $this->mBidtable
as $k => $v ) {
1314 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1316 foreach ( $this->mUnidtable
as $k => $a ) {
1317 foreach ( $a as $from => $to ) {
1318 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1319 "$codesep$to$varsep";
1326 * Parse rules conversion.
1333 function getRuleConvertedStr( $variant ) {
1334 $bidtable = $this->mBidtable
;
1335 $unidtable = $this->mUnidtable
;
1337 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1338 return $this->mRules
;
1340 // display current variant in bidirectional array
1341 $disp = $this->getTextInBidtable( $variant );
1342 // or display current variant in fallbacks
1344 $disp = $this->getTextInBidtable(
1345 $this->mConverter
->getVariantFallbacks( $variant ) );
1347 // or display current variant in unidirectional array
1348 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1349 $disp = array_values( $unidtable[$variant] );
1352 // or display frist text under disable manual convert
1353 if ( !$disp && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1354 if ( count( $bidtable ) > 0 ) {
1355 $disp = array_values( $bidtable );
1358 $disp = array_values( $unidtable );
1359 $disp = array_values( $disp[0] );
1368 * Similar to getRuleConvertedStr(), but this prefers to use original
1369 * page title if $variant === $this->mConverter->mMainLanguageCode
1370 * and may return false in this case (so this title conversion rule
1371 * will be ignored and the original title is shown).
1374 * @param $variant The variant code to display page title in
1375 * @return String|false The converted title or false if just page name
1377 function getRuleConvertedTitle( $variant ) {
1378 if ( $variant === $this->mConverter
->mMainLanguageCode
) {
1379 // If a string targeting exactly this variant is set,
1380 // use it. Otherwise, just return false, so the real
1381 // page name can be shown (and because variant === main,
1382 // there'll be no further automatic conversion).
1383 $disp = $this->getTextInBidtable( $variant );
1387 if ( array_key_exists( $variant, $this->mUnidtable
) ) {
1388 $disp = array_values( $this->mUnidtable
[$variant] );
1391 // Assigned above or still false.
1394 return $this->getRuleConvertedStr( $variant );
1399 * Generate conversion table for all text.
1402 function generateConvTable() {
1403 // Special case optimisation
1404 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1405 $this->mConvTable
= array();
1409 $bidtable = $this->mBidtable
;
1410 $unidtable = $this->mUnidtable
;
1411 $manLevel = $this->mConverter
->mManualLevel
;
1414 foreach ( $this->mConverter
->mVariants
as $v ) {
1415 /* for bidirectional array
1416 fill in the missing variants, if any,
1418 if ( !isset( $bidtable[$v] ) ) {
1420 $this->mConverter
->getVariantFallbacks( $v );
1421 $vf = $this->getTextInBidtable( $variantFallbacks );
1423 $bidtable[$v] = $vf;
1427 if ( isset( $bidtable[$v] ) ) {
1428 foreach ( $vmarked as $vo ) {
1429 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1430 // or -{H|zh:WordZh;zh-tw:WordTw}-
1431 // or -{-|zh:WordZh;zh-tw:WordTw}-
1432 // to introduce a custom mapping between
1433 // words WordZh and WordTw in the whole text
1434 if ( $manLevel[$v] == 'bidirectional' ) {
1435 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1437 if ( $manLevel[$vo] == 'bidirectional' ) {
1438 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1443 /* for unidirectional array fill to convert tables */
1444 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1445 && isset( $unidtable[$v] )
1447 if ( isset( $this->mConvTable
[$v] ) ) {
1448 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1450 $this->mConvTable
[$v] = $unidtable[$v];
1457 * Parse rules and flags.
1458 * @param $variant String: variant language code
1460 public function parse( $variant = null ) {
1462 $variant = $this->mConverter
->getPreferredVariant();
1465 $this->parseFlags();
1466 $flags = $this->mFlags
;
1468 // convert to specified variant
1469 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1470 if ( $this->mVariantFlags
) {
1471 // check if current variant in flags
1472 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1473 // then convert <text to convert> to current language
1474 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1477 // if current variant no in flags,
1478 // then we check its fallback variants.
1480 $this->mConverter
->getVariantFallbacks( $variant );
1481 if ( is_array( $variantFallbacks ) ) {
1482 foreach ( $variantFallbacks as $variantFallback ) {
1483 // if current variant's fallback exist in flags
1484 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1485 // then convert <text to convert> to fallback language
1487 $this->mConverter
->autoConvert( $this->mRules
,
1494 $this->mFlags
= $flags = array( 'R' => true );
1497 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1498 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1499 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1500 $this->parseRules();
1502 $rules = $this->mRules
;
1504 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1505 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1506 // fill all variants if text in -{A/H/-|text} without rules
1507 foreach ( $this->mConverter
->mVariants
as $v ) {
1508 $this->mBidtable
[$v] = $rules;
1510 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1511 $this->mFlags
= $flags = array( 'R' => true );
1515 $this->mRuleDisplay
= false;
1516 foreach ( $flags as $flag => $unused ) {
1519 // if we don't do content convert, still strip the -{}- tags
1520 $this->mRuleDisplay
= $rules;
1523 // process N flag: output current variant name
1524 $ruleVar = trim( $rules );
1525 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1526 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1528 $this->mRuleDisplay
= '';
1532 // process D flag: output rules description
1533 $this->mRuleDisplay
= $this->getRulesDesc();
1536 // process H,- flag or T only: output nothing
1537 $this->mRuleDisplay
= '';
1540 $this->mRulesAction
= 'remove';
1541 $this->mRuleDisplay
= '';
1544 $this->mRulesAction
= 'add';
1545 $this->mRuleDisplay
= '';
1548 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1551 $this->mRuleTitle
= $this->getRuleConvertedTitle( $variant );
1552 $this->mRuleDisplay
= '';
1555 // ignore unknown flags (but see error case below)
1558 if ( $this->mRuleDisplay
=== false ) {
1559 $this->mRuleDisplay
= '<span class="error">'
1560 . wfMessage( 'converter-manual-rule-error' )->inContentLanguage()->escaped()
1564 $this->generateConvTable();
1568 * @todo FIXME: code this function :)
1570 public function hasRules() {
1575 * Get display text on markup -{...}-
1578 public function getDisplay() {
1579 return $this->mRuleDisplay
;
1583 * Get converted title.
1586 public function getTitle() {
1587 return $this->mRuleTitle
;
1591 * Return how deal with conversion rules.
1594 public function getRulesAction() {
1595 return $this->mRulesAction
;
1599 * Get conversion table. (bidirectional and unidirectional
1603 public function getConvTable() {
1604 return $this->mConvTable
;
1608 * Get conversion rules string.
1611 public function getRules() {
1612 return $this->mRules
;
1616 * Get conversion flags.
1619 public function getFlags() {
1620 return $this->mFlags
;