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 6';
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
106 // (but no display in placed code)
107 'N' => 'N' // current variant name
109 $this->mFlags
= array_merge( $defaultflags, $flags );
110 foreach ( $this->mVariants
as $v ) {
111 if ( array_key_exists( $v, $manualLevel ) ) {
112 $this->mManualLevel
[$v] = $manualLevel[$v];
114 $this->mManualLevel
[$v] = 'bidirectional';
116 $this->mFlags
[$v] = $v;
121 * Get all valid variants.
122 * Call this instead of using $this->mVariants directly.
124 * @return Array: contains all valid variants
126 public function getVariants() {
127 return $this->mVariants
;
131 * In case some variant is not defined in the markup, we need
132 * to have some fallback. For example, in zh, normally people
133 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
134 * when zh-sg is preferred but not defined, we will pick zh-hans
135 * in this case. Right now this is only used by zh.
137 * @param $variant String: the language code of the variant
138 * @return String|array: The code of the fallback language or the
139 * main code if there is no fallback
141 public function getVariantFallbacks( $variant ) {
142 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
143 return $this->mVariantFallbacks
[$variant];
145 return $this->mMainLanguageCode
;
149 * Get the title produced by the conversion rule.
150 * @return String: The converted title text
152 public function getConvRuleTitle() {
153 return $this->mConvRuleTitle
;
157 * Get preferred language variant.
158 * @return String: the preferred language code
160 public function getPreferredVariant() {
161 global $wgDefaultLanguageVariant, $wgUser;
163 $req = $this->getURLVariant();
165 if ( $wgUser->isLoggedIn() && !$req ) {
166 $req = $this->getUserVariant();
168 $req = $this->getHeaderVariant();
171 if ( $wgDefaultLanguageVariant && !$req ) {
172 $req = $this->validateVariant( $wgDefaultLanguageVariant );
175 // This function, unlike the other get*Variant functions, is
176 // not memoized (i.e. there return value is not cached) since
177 // new information might appear during processing after this
179 if ( $this->validateVariant( $req ) ) {
182 return $this->mMainLanguageCode
;
186 * Get default variant.
187 * This function would not be affected by user's settings
188 * @return String: the default variant code
190 public function getDefaultVariant() {
191 global $wgDefaultLanguageVariant;
193 $req = $this->getURLVariant();
196 $req = $this->getHeaderVariant();
199 if ( $wgDefaultLanguageVariant && !$req ) {
200 $req = $this->validateVariant( $wgDefaultLanguageVariant );
206 return $this->mMainLanguageCode
;
210 * Validate the variant
211 * @param $variant String: the variant to validate
212 * @return Mixed: returns the variant if it is valid, null otherwise
214 public function validateVariant( $variant = null ) {
215 if ( $variant !== null && in_array( $variant, $this->mVariants
) ) {
222 * Get the variant specified in the URL
224 * @return Mixed: variant if one found, false otherwise.
226 public function getURLVariant() {
229 if ( $this->mURLVariant
) {
230 return $this->mURLVariant
;
233 // see if the preference is set in the request
234 $ret = $wgRequest->getText( 'variant' );
237 $ret = $wgRequest->getVal( 'uselang' );
240 return $this->mURLVariant
= $this->validateVariant( $ret );
244 * Determine if the user has a variant set.
246 * @return Mixed: variant if one found, false otherwise.
248 protected function getUserVariant() {
249 global $wgUser, $wgContLang;
251 // memoizing this function wreaks havoc on parserTest.php
253 if ( $this->mUserVariant ) {
254 return $this->mUserVariant;
258 // Get language variant preference from logged in users
259 // Don't call this on stub objects because that causes infinite
260 // recursion during initialisation
261 if ( $wgUser->isLoggedIn() ) {
262 if ( $this->mMainLanguageCode
== $wgContLang->getCode() ) {
263 $ret = $wgUser->getOption( 'variant' );
265 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode
);
268 // figure out user lang without constructing wgLang to avoid
269 // infinite recursion
270 $ret = $wgUser->getOption( 'language' );
273 return $this->mUserVariant
= $this->validateVariant( $ret );
277 * Determine the language variant from the Accept-Language header.
279 * @return Mixed: variant if one found, false otherwise.
281 protected function getHeaderVariant() {
284 if ( $this->mHeaderVariant
) {
285 return $this->mHeaderVariant
;
288 // see if some supported language variant is set in the
290 $languages = array_keys( $wgRequest->getAcceptLang() );
291 if ( empty( $languages ) ) {
295 $fallbackLanguages = array();
296 foreach ( $languages as $language ) {
297 $this->mHeaderVariant
= $this->validateVariant( $language );
298 if ( $this->mHeaderVariant
) {
302 // To see if there are fallbacks of current language.
303 // We record these fallback variants, and process
305 $fallbacks = $this->getVariantFallbacks( $language );
306 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
307 $fallbackLanguages[] = $fallbacks;
308 } elseif ( is_array( $fallbacks ) ) {
310 array_merge( $fallbackLanguages, $fallbacks );
314 if ( !$this->mHeaderVariant
) {
315 // process fallback languages now
316 $fallback_languages = array_unique( $fallbackLanguages );
317 foreach ( $fallback_languages as $language ) {
318 $this->mHeaderVariant
= $this->validateVariant( $language );
319 if ( $this->mHeaderVariant
) {
325 return $this->mHeaderVariant
;
329 * Dictionary-based conversion.
330 * This function would not parse the conversion rules.
331 * If you want to parse rules, try to use convert() or
334 * @param $text String the text to be converted
335 * @param $toVariant bool|string the target language code
336 * @return String the converted text
338 public function autoConvert( $text, $toVariant = false ) {
339 wfProfileIn( __METHOD__
);
344 $toVariant = $this->getPreferredVariant();
346 wfProfileOut( __METHOD__
);
351 if ( $this->guessVariant( $text, $toVariant ) ) {
352 wfProfileOut( __METHOD__
);
356 /* we convert everything except:
357 1. HTML markups (anything between < and >)
359 3. placeholders created by the parser
362 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
363 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
368 // this one is needed when the text is inside an HTML markup
369 $htmlfix = '|<[^>]+$|^[^<>]*>';
371 // disable convert to variants between <code> tags
372 $codefix = '<code>.+?<\/code>|';
373 // disable conversion of <script> tags
374 $scriptfix = '<script.*?>.*?<\/script>|';
375 // disable conversion of <pre> tags
376 $prefix = '<pre.*?>.*?<\/pre>|';
378 $reg = '/' . $codefix . $scriptfix . $prefix .
379 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
384 // Guard against delimiter nulls in the input
385 $text = str_replace( "\000", '', $text );
387 $markupMatches = null;
388 $elementMatches = null;
389 while ( $startPos < strlen( $text ) ) {
390 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
391 $elementPos = $markupMatches[0][1];
392 $element = $markupMatches[0][0];
394 $elementPos = strlen( $text );
398 // Queue the part before the markup for translation in a batch
399 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
401 // Advance to the next position
402 $startPos = $elementPos +
strlen( $element );
404 // Translate any alt or title attributes inside the matched element
405 if ( $element !== '' && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element,
408 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
410 foreach ( array( 'title', 'alt' ) as $attrName ) {
411 if ( !isset( $attrs[$attrName] ) ) {
414 $attr = $attrs[$attrName];
415 // Don't convert URLs
416 if ( !strpos( $attr, '://' ) ) {
417 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
420 // Remove HTML tags to avoid disrupting the layout
421 $attr = preg_replace( '/<[^>]+>/', '', $attr );
422 if ( $attr !== $attrs[$attrName] ) {
423 $attrs[$attrName] = $attr;
428 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
432 $literalBlob .= $element . "\000";
435 // Do the main translation batch
436 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
438 // Put the output back together
439 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
440 $literalIter = StringUtils
::explode( "\000", $literalBlob );
442 while ( $translatedIter->valid() && $literalIter->valid() ) {
443 $output .= $translatedIter->current();
444 $output .= $literalIter->current();
445 $translatedIter->next();
446 $literalIter->next();
449 wfProfileOut( __METHOD__
);
454 * Translate a string to a variant.
455 * Doesn't parse rules or do any of that other stuff, for that use
456 * convert() or convertTo().
458 * @param $text String: text to convert
459 * @param $variant String: variant language code
460 * @return String: translated text
462 public function translate( $text, $variant ) {
463 wfProfileIn( __METHOD__
);
464 // If $text is empty or only includes spaces, do nothing
465 // Otherwise translate it
466 if ( trim( $text ) ) {
468 $text = $this->mTables
[$variant]->replace( $text );
470 wfProfileOut( __METHOD__
);
475 * Call translate() to convert text to all valid variants.
477 * @param $text String: the text to be converted
478 * @return Array: variant => converted text
480 public function autoConvertToAllVariants( $text ) {
481 wfProfileIn( __METHOD__
);
485 foreach ( $this->mVariants
as $variant ) {
486 $ret[$variant] = $this->translate( $text, $variant );
489 wfProfileOut( __METHOD__
);
494 * Convert link text to all valid variants.
495 * In the first, this function only convert text outside the
496 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
497 * titles, the text will get all converted always.
498 * So I removed this feature and deprecated the function.
500 * @param $text String: the text to be converted
501 * @return Array: variant => converted text
502 * @deprecated since 1.17 Use autoConvertToAllVariants() instead
504 public function convertLinkToAllVariants( $text ) {
505 return $this->autoConvertToAllVariants( $text );
509 * Apply manual conversion rules.
511 * @param $convRule ConverterRule Object of ConverterRule
513 protected function applyManualConv( $convRule ) {
514 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
516 // Bug 24072: $mConvRuleTitle was overwritten by other manual
517 // rule(s) not for title, this breaks the title conversion.
518 $newConvRuleTitle = $convRule->getTitle();
519 if ( $newConvRuleTitle ) {
520 // So I add an empty check for getTitle()
521 $this->mConvRuleTitle
= $newConvRuleTitle;
524 // merge/remove manual conversion rules to/from global table
525 $convTable = $convRule->getConvTable();
526 $action = $convRule->getRulesAction();
527 foreach ( $convTable as $variant => $pair ) {
528 if ( !$this->validateVariant( $variant ) ) {
532 if ( $action == 'add' ) {
533 foreach ( $pair as $from => $to ) {
534 // to ensure that $from and $to not be left blank
535 // so $this->translate() could always return a string
536 if ( $from ||
$to ) {
537 // more efficient than array_merge(), about 2.5 times.
538 $this->mTables
[$variant]->setPair( $from, $to );
541 } elseif ( $action == 'remove' ) {
542 $this->mTables
[$variant]->removeArray( $pair );
548 * Auto convert a Title object to a readable string in the
551 * @param $title Title a object of Title
552 * @return String: converted title text
554 public function convertTitle( $title ) {
555 $variant = $this->getPreferredVariant();
556 $index = $title->getNamespace();
557 if ( $index !== NS_MAIN
) {
558 $text = $this->convertNamespace( $index ) . ':';
562 $text .= $this->translate( $title->getText(), $variant );
567 * Get the namespace display name in the preferred variant.
569 * @param $index int namespace id
570 * @return String: namespace name for display
572 public function convertNamespace( $index ) {
573 $variant = $this->getPreferredVariant();
574 if ( $index === NS_MAIN
) {
577 // First check if a message gives a converted name in the target variant.
578 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
579 if ( $nsConvMsg->exists() ) {
580 return $nsConvMsg->plain();
582 // Then check if a message gives a converted name in content language
583 // which needs extra translation to the target variant.
584 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
585 if ( $nsConvMsg->exists() ) {
586 return $this->translate( $nsConvMsg->plain(), $variant );
588 // No message exists, retrieve it from the target variant's namespace names.
589 $langObj = $this->mLangObj
->factory( $variant );
590 return $langObj->getFormattedNsText( $index );
595 * Convert text to different variants of a language. The automatic
596 * conversion is done in autoConvert(). Here we parse the text
597 * marked with -{}-, which specifies special conversions of the
598 * text that can not be accomplished in autoConvert().
600 * Syntax of the markup:
601 * -{code1:text1;code2:text2;...}- or
602 * -{flags|code1:text1;code2:text2;...}- or
603 * -{text}- in which case no conversion should take place for text
605 * @param $text String: text to be converted
606 * @return String: converted text
608 public function convert( $text ) {
609 $variant = $this->getPreferredVariant();
610 return $this->convertTo( $text, $variant );
614 * Same as convert() except a extra parameter to custom variant.
616 * @param $text String: text to be converted
617 * @param $variant String: the target variant code
618 * @return String: converted text
620 public function convertTo( $text, $variant ) {
621 global $wgDisableLangConversion;
622 if ( $wgDisableLangConversion ) {
625 // Reset converter state for a new converter run.
626 $this->mConvRuleTitle
= false;
627 return $this->recursiveConvertTopLevel( $text, $variant );
631 * Recursively convert text on the outside. Allow to use nested
632 * markups to custom rules.
634 * @param $text String: text to be converted
635 * @param $variant String: the target variant code
636 * @param $depth Integer: depth of recursion
637 * @return String: converted text
639 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
642 $length = strlen( $text );
643 $shouldConvert = !$this->guessVariant( $text, $variant );
645 while ( $startPos < $length ) {
646 $pos = strpos( $text, '-{', $startPos );
648 if ( $pos === false ) {
649 // No more markup, append final segment
650 $fragment = substr( $text, $startPos );
651 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
656 // Append initial segment
657 $fragment = substr( $text, $startPos, $pos - $startPos );
658 $out .= $shouldConvert ?
$this->autoConvert( $fragment, $variant ) : $fragment;
663 // Do recursive conversion
664 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
671 * Recursively convert text on the inside.
673 * @param $text String: text to be converted
674 * @param $variant String: the target variant code
675 * @param $startPos int
676 * @param $depth Integer: depth of recursion
678 * @throws MWException
679 * @return String: converted text
681 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
682 // Quick sanity check (no function calls)
683 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
684 throw new MWException( __METHOD__
. ': invalid input string' );
689 $warningDone = false;
690 $length = strlen( $text );
692 while ( $startPos < $length ) {
694 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
704 // Append initial segment
705 $inner .= substr( $text, $startPos, $pos - $startPos );
713 if ( $depth >= $this->mMaxDepth
) {
715 if ( !$warningDone ) {
716 $inner .= '<span class="error">' .
717 wfMessage( 'language-converter-depth-warning' )
718 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
725 // Recursively parse another rule
726 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
731 $rule = new ConverterRule( $inner, $this );
732 $rule->parse( $variant );
733 $this->applyManualConv( $rule );
734 return $rule->getDisplay();
736 throw new MWException( __METHOD__
. ': invalid regex match' );
741 if ( $startPos < $length ) {
742 $inner .= substr( $text, $startPos );
745 return '-{' . $this->autoConvert( $inner, $variant );
749 * If a language supports multiple variants, it is possible that
750 * non-existing link in one variant actually exists in another variant.
751 * This function tries to find it. See e.g. LanguageZh.php
753 * @param $link String: the name of the link
754 * @param $nt Mixed: the title object of the link
755 * @param $ignoreOtherCond Boolean: to disable other conditions when
756 * we need to transclude a template or update a category's link
757 * @return Null, the input parameters may be modified upon return
759 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
760 # If the article has already existed, there is no need to
761 # check it again, otherwise it may cause a fault.
762 if ( is_object( $nt ) && $nt->exists() ) {
766 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
768 $isredir = $wgRequest->getText( 'redirect', 'yes' );
769 $action = $wgRequest->getText( 'action' );
770 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
771 $disableLinkConversion = $wgDisableLangConversion
772 ||
$wgDisableTitleConversion;
773 $linkBatch = new LinkBatch();
777 if ( $disableLinkConversion ||
778 ( !$ignoreOtherCond &&
781 ||
$action == 'submit'
782 ||
$linkconvert == 'no'
783 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
787 if ( is_object( $nt ) ) {
788 $ns = $nt->getNamespace();
791 $variants = $this->autoConvertToAllVariants( $link );
792 if ( !$variants ) { // give up
798 foreach ( $variants as $v ) {
800 $varnt = Title
::newFromText( $v, $ns );
801 if ( !is_null( $varnt ) ) {
802 $linkBatch->addObj( $varnt );
808 // fetch all variants in single query
809 $linkBatch->execute();
811 foreach ( $titles as $varnt ) {
812 if ( $varnt->getArticleID() > 0 ) {
814 $link = $varnt->getText();
821 * Returns language specific hash options.
825 public function getExtraHashOptions() {
826 $variant = $this->getPreferredVariant();
827 return '!' . $variant;
831 * Guess if a text is written in a variant. This should be implemented in subclasses.
833 * @param string $text the text to be checked
834 * @param string $variant language code of the variant to be checked for
835 * @return bool true if $text appears to be written in $variant, false if not
837 * @author Nikola Smolenski <smolensk@eunet.rs>
840 public function guessVariant( $text, $variant ) {
845 * Load default conversion tables.
846 * This method must be implemented in derived class.
849 * @throws MWException
851 function loadDefaultTables() {
852 $name = get_class( $this );
853 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
857 * Load conversion tables either from the cache or the disk.
859 * @param $fromCache Boolean: load from memcached? Defaults to true.
861 function loadTables( $fromCache = true ) {
862 global $wgLangConvMemc;
864 if ( $this->mTablesLoaded
) {
868 wfProfileIn( __METHOD__
);
869 $this->mTablesLoaded
= true;
870 $this->mTables
= false;
872 wfProfileIn( __METHOD__
. '-cache' );
873 $this->mTables
= $wgLangConvMemc->get( $this->mCacheKey
);
874 wfProfileOut( __METHOD__
. '-cache' );
877 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
878 wfProfileIn( __METHOD__
. '-recache' );
879 // not in cache, or we need a fresh reload.
880 // We will first load the default tables
881 // then update them using things in MediaWiki:Conversiontable/*
882 $this->loadDefaultTables();
883 foreach ( $this->mVariants
as $var ) {
884 $cached = $this->parseCachedTable( $var );
885 $this->mTables
[$var]->mergeArray( $cached );
888 $this->postLoadTables();
889 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
891 $wgLangConvMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
892 wfProfileOut( __METHOD__
. '-recache' );
894 wfProfileOut( __METHOD__
);
898 * Hook for post processing after conversion tables are loaded.
900 function postLoadTables() { }
903 * Reload the conversion tables.
907 function reloadTables() {
908 if ( $this->mTables
) {
909 unset( $this->mTables
);
911 $this->mTablesLoaded
= false;
912 $this->loadTables( false );
916 * Parse the conversion table stored in the cache.
918 * The tables should be in blocks of the following form:
925 * To make the tables more manageable, subpages are allowed
926 * and will be parsed recursively if $recursive == true.
928 * @param $code String: language code
929 * @param $subpage String: subpage name
930 * @param $recursive Boolean: parse subpages recursively? Defaults to true.
934 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
935 static $parsed = array();
937 $key = 'Conversiontable/' . $code;
939 $key .= '/' . $subpage;
941 if ( array_key_exists( $key, $parsed ) ) {
945 $parsed[$key] = true;
947 if ( $subpage === '' ) {
948 $txt = MessageCache
::singleton()->getMsgFromNamespace( $key, $code );
951 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
952 if ( $title && $title->exists() ) {
953 $revision = Revision
::newFromTitle( $title );
955 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
956 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
959 // @todo in the future, use a specialized content model, perhaps based on json!
964 # Nothing to parse if there's no text
965 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
969 // get all subpage links of the form
970 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
971 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
973 $subs = StringUtils
::explode( '[[', $txt );
975 foreach ( $subs as $sub ) {
976 $link = explode( ']]', $sub, 2 );
977 if ( count( $link ) != 2 ) {
980 $b = explode( '|', $link[0], 2 );
981 $b = explode( '/', trim( $b[0] ), 3 );
982 if ( count( $b ) == 3 ) {
988 if ( $b[0] == $linkhead && $b[1] == $code ) {
989 $sublinks[] = $sublink;
993 // parse the mappings in this page
994 $blocks = StringUtils
::explode( '-{', $txt );
997 foreach ( $blocks as $block ) {
999 // Skip the part before the first -{
1003 $mappings = explode( '}-', $block, 2 );
1004 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
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
1104 public function armourMath( $text ) {
1105 // convert '-{' and '}-' to '-{' and '}-' to prevent
1106 // any unwanted markup appearing in the math image tag.
1107 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
1112 * Get the cached separator pattern for ConverterRule::parseRules()
1114 function getVarSeparatorPattern() {
1115 if ( is_null( $this->mVarSeparatorPattern
) ) {
1116 // varsep_pattern for preg_split:
1117 // text should be splited by ";" only if a valid variant
1118 // name exist after the markup, for example:
1119 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1120 // <span style="font-size:120%;">yyy</span>;}-
1121 // we should split it as:
1123 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1124 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1128 foreach ( $this->mVariants
as $variant ) {
1129 // zh-hans:xxx;zh-hant:yyy
1130 $pat .= $variant . '\s*:|';
1131 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1132 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1135 $this->mVarSeparatorPattern
= $pat;
1137 return $this->mVarSeparatorPattern
;
1142 * Parser for rules of language conversion , parse rules in -{ }- tag.
1144 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1146 class ConverterRule
{
1147 public $mText; // original text in -{text}-
1148 public $mConverter; // LanguageConverter object
1149 public $mRuleDisplay = '';
1150 public $mRuleTitle = false;
1151 public $mRules = '';// string : the text of the rules
1152 public $mRulesAction = 'none';
1153 public $mFlags = array();
1154 public $mVariantFlags = array();
1155 public $mConvTable = array();
1156 public $mBidtable = array();// array of the translation in each variant
1157 public $mUnidtable = array();// array of the translation in each variant
1162 * @param $text String: the text between -{ and }-
1163 * @param $converter LanguageConverter object
1165 public function __construct( $text, $converter ) {
1166 $this->mText
= $text;
1167 $this->mConverter
= $converter;
1171 * Check if variants array in convert array.
1173 * @param $variants Array or string: variant language code
1174 * @return String: translated text
1176 public function getTextInBidtable( $variants ) {
1177 $variants = (array)$variants;
1181 foreach ( $variants as $variant ) {
1182 if ( isset( $this->mBidtable
[$variant] ) ) {
1183 return $this->mBidtable
[$variant];
1190 * Parse flags with syntax -{FLAG| ... }-
1193 function parseFlags() {
1194 $text = $this->mText
;
1196 $variantFlags = array();
1198 $sepPos = strpos( $text, '|' );
1199 if ( $sepPos !== false ) {
1200 $validFlags = $this->mConverter
->mFlags
;
1201 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1202 foreach ( $f as $ff ) {
1204 if ( isset( $validFlags[$ff] ) ) {
1205 $flags[$validFlags[$ff]] = true;
1208 $text = strval( substr( $text, $sepPos +
1 ) );
1213 } elseif ( isset( $flags['R'] ) ) {
1214 $flags = array( 'R' => true );// remove other flags
1215 } elseif ( isset( $flags['N'] ) ) {
1216 $flags = array( 'N' => true );// remove other flags
1217 } elseif ( isset( $flags['-'] ) ) {
1218 $flags = array( '-' => true );// remove other flags
1219 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1221 } elseif ( isset( $flags['H'] ) ) {
1222 // replace A flag, and remove other flags except T
1223 $temp = array( '+' => true, 'H' => true );
1224 if ( isset( $flags['T'] ) ) {
1227 if ( isset( $flags['D'] ) ) {
1232 if ( isset( $flags['A'] ) ) {
1236 if ( isset( $flags['D'] ) ) {
1237 unset( $flags['S'] );
1239 // try to find flags like "zh-hans", "zh-hant"
1240 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1241 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1242 if ( $variantFlags ) {
1243 $variantFlags = array_flip( $variantFlags );
1247 $this->mVariantFlags
= $variantFlags;
1248 $this->mRules
= $text;
1249 $this->mFlags
= $flags;
1253 * Generate conversion table.
1256 function parseRules() {
1257 $rules = $this->mRules
;
1258 $bidtable = array();
1259 $unidtable = array();
1260 $variants = $this->mConverter
->mVariants
;
1261 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1263 $choice = preg_split( $varsep_pattern, $rules );
1265 foreach ( $choice as $c ) {
1266 $v = explode( ':', $c, 2 );
1267 if ( count( $v ) != 2 ) {
1268 // syntax error, skip
1271 $to = trim( $v[1] );
1273 $u = explode( '=>', $v, 2 );
1274 // if $to is empty, strtr() could return a wrong result
1275 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1276 $bidtable[$v] = $to;
1277 } elseif ( count( $u ) == 2 ) {
1278 $from = trim( $u[0] );
1280 if ( array_key_exists( $v, $unidtable )
1281 && !is_array( $unidtable[$v] )
1283 && in_array( $v, $variants ) ) {
1284 $unidtable[$v] = array( $from => $to );
1285 } elseif ( $to && in_array( $v, $variants ) ) {
1286 $unidtable[$v][$from] = $to;
1289 // syntax error, pass
1290 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1291 $bidtable = array();
1292 $unidtable = array();
1296 $this->mBidtable
= $bidtable;
1297 $this->mUnidtable
= $unidtable;
1305 function getRulesDesc() {
1306 $codesep = $this->mConverter
->mDescCodeSep
;
1307 $varsep = $this->mConverter
->mDescVarSep
;
1309 foreach ( $this->mBidtable
as $k => $v ) {
1310 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1312 foreach ( $this->mUnidtable
as $k => $a ) {
1313 foreach ( $a as $from => $to ) {
1314 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1315 "$codesep$to$varsep";
1322 * Parse rules conversion.
1329 function getRuleConvertedStr( $variant ) {
1330 $bidtable = $this->mBidtable
;
1331 $unidtable = $this->mUnidtable
;
1333 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1334 return $this->mRules
;
1336 // display current variant in bidirectional array
1337 $disp = $this->getTextInBidtable( $variant );
1338 // or display current variant in fallbacks
1340 $disp = $this->getTextInBidtable(
1341 $this->mConverter
->getVariantFallbacks( $variant ) );
1343 // or display current variant in unidirectional array
1344 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1345 $disp = array_values( $unidtable[$variant] );
1348 // or display frist text under disable manual convert
1350 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1351 if ( count( $bidtable ) > 0 ) {
1352 $disp = array_values( $bidtable );
1355 $disp = array_values( $unidtable );
1356 $disp = array_values( $disp[0] );
1365 * Similar to getRuleConvertedStr(), but this prefers to use original
1366 * page title if $variant === $this->mConverter->mMainLanguageCode
1367 * and may return false in this case (so this title conversion rule
1368 * will be ignored and the original title is shown).
1371 * @param $variant The variant code to display page title in
1372 * @return String|false The converted title or false if just page name
1374 function getRuleConvertedTitle( $variant ) {
1375 if ( $variant === $this->mConverter
->mMainLanguageCode
) {
1376 // If a string targeting exactly this variant is set,
1377 // use it. Otherwise, just return false, so the real
1378 // page name can be shown (and because variant === main,
1379 // there'll be no further automatic conversion).
1380 $disp = $this->getTextInBidtable( $variant );
1384 if ( array_key_exists( $variant, $this->mUnidtable
) ) {
1385 $disp = array_values( $this->mUnidtable
[$variant] );
1388 // Assigned above or still false.
1391 return $this->getRuleConvertedStr( $variant );
1396 * Generate conversion table for all text.
1399 function generateConvTable() {
1400 // Special case optimisation
1401 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1402 $this->mConvTable
= array();
1406 $bidtable = $this->mBidtable
;
1407 $unidtable = $this->mUnidtable
;
1408 $manLevel = $this->mConverter
->mManualLevel
;
1411 foreach ( $this->mConverter
->mVariants
as $v ) {
1412 /* for bidirectional array
1413 fill in the missing variants, if any,
1415 if ( !isset( $bidtable[$v] ) ) {
1417 $this->mConverter
->getVariantFallbacks( $v );
1418 $vf = $this->getTextInBidtable( $variantFallbacks );
1420 $bidtable[$v] = $vf;
1424 if ( isset( $bidtable[$v] ) ) {
1425 foreach ( $vmarked as $vo ) {
1426 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1427 // or -{H|zh:WordZh;zh-tw:WordTw}-
1428 // or -{-|zh:WordZh;zh-tw:WordTw}-
1429 // to introduce a custom mapping between
1430 // words WordZh and WordTw in the whole text
1431 if ( $manLevel[$v] == 'bidirectional' ) {
1432 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1434 if ( $manLevel[$vo] == 'bidirectional' ) {
1435 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1440 /* for unidirectional array fill to convert tables */
1441 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1442 && isset( $unidtable[$v] ) )
1444 if ( isset( $this->mConvTable
[$v] ) ) {
1445 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1447 $this->mConvTable
[$v] = $unidtable[$v];
1454 * Parse rules and flags.
1455 * @param $variant String: variant language code
1457 public function parse( $variant = null ) {
1459 $variant = $this->mConverter
->getPreferredVariant();
1462 $this->parseFlags();
1463 $flags = $this->mFlags
;
1465 // convert to specified variant
1466 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1467 if ( $this->mVariantFlags
) {
1468 // check if current variant in flags
1469 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1470 // then convert <text to convert> to current language
1471 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1473 } else { // if current variant no in flags,
1474 // then we check its fallback variants.
1476 $this->mConverter
->getVariantFallbacks( $variant );
1477 if ( is_array( $variantFallbacks ) ) {
1478 foreach ( $variantFallbacks as $variantFallback ) {
1479 // if current variant's fallback exist in flags
1480 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1481 // then convert <text to convert> to fallback language
1483 $this->mConverter
->autoConvert( $this->mRules
,
1490 $this->mFlags
= $flags = array( 'R' => true );
1493 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1494 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1495 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1496 $this->parseRules();
1498 $rules = $this->mRules
;
1500 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1501 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1502 // fill all variants if text in -{A/H/-|text} without rules
1503 foreach ( $this->mConverter
->mVariants
as $v ) {
1504 $this->mBidtable
[$v] = $rules;
1506 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1507 $this->mFlags
= $flags = array( 'R' => true );
1511 $this->mRuleDisplay
= false;
1512 foreach ( $flags as $flag => $unused ) {
1515 // if we don't do content convert, still strip the -{}- tags
1516 $this->mRuleDisplay
= $rules;
1519 // process N flag: output current variant name
1520 $ruleVar = trim( $rules );
1521 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1522 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1524 $this->mRuleDisplay
= '';
1528 // process D flag: output rules description
1529 $this->mRuleDisplay
= $this->getRulesDesc();
1532 // process H,- flag or T only: output nothing
1533 $this->mRuleDisplay
= '';
1536 $this->mRulesAction
= 'remove';
1537 $this->mRuleDisplay
= '';
1540 $this->mRulesAction
= 'add';
1541 $this->mRuleDisplay
= '';
1544 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1547 $this->mRuleTitle
= $this->getRuleConvertedTitle( $variant );
1548 $this->mRuleDisplay
= '';
1551 // ignore unknown flags (but see error case below)
1554 if ( $this->mRuleDisplay
=== false ) {
1555 $this->mRuleDisplay
= '<span class="error">'
1556 . wfMessage( 'converter-manual-rule-error' )->inContentLanguage()->escaped()
1560 $this->generateConvTable();
1564 * @todo FIXME: code this function :)
1566 public function hasRules() {
1571 * Get display text on markup -{...}-
1574 public function getDisplay() {
1575 return $this->mRuleDisplay
;
1579 * Get converted title.
1582 public function getTitle() {
1583 return $this->mRuleTitle
;
1587 * Return how deal with conversion rules.
1590 public function getRulesAction() {
1591 return $this->mRulesAction
;
1595 * Get conversion table. (bidirectional and unidirectional
1599 public function getConvTable() {
1600 return $this->mConvTable
;
1604 * Get conversion rules string.
1607 public function getRules() {
1608 return $this->mRules
;
1612 * Get conversion flags.
1615 public function getFlags() {
1616 return $this->mFlags
;