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() {
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 $ret = $wgUser->getOption( 'variant' );
264 // figure out user lang without constructing wgLang to avoid
265 // infinite recursion
266 $ret = $wgUser->getOption( 'language' );
269 return $this->mUserVariant
= $this->validateVariant( $ret );
273 * Determine the language variant from the Accept-Language header.
275 * @return Mixed: variant if one found, false otherwise.
277 protected function getHeaderVariant() {
280 if ( $this->mHeaderVariant
) {
281 return $this->mHeaderVariant
;
284 // see if some supported language variant is set in the
286 $languages = array_keys( $wgRequest->getAcceptLang() );
287 if ( empty( $languages ) ) {
291 $fallbackLanguages = array();
292 foreach ( $languages as $language ) {
293 $this->mHeaderVariant
= $this->validateVariant( $language );
294 if ( $this->mHeaderVariant
) {
298 // To see if there are fallbacks of current language.
299 // We record these fallback variants, and process
301 $fallbacks = $this->getVariantFallbacks( $language );
302 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
303 $fallbackLanguages[] = $fallbacks;
304 } elseif ( is_array( $fallbacks ) ) {
306 array_merge( $fallbackLanguages, $fallbacks );
310 if ( !$this->mHeaderVariant
) {
311 // process fallback languages now
312 $fallback_languages = array_unique( $fallbackLanguages );
313 foreach ( $fallback_languages as $language ) {
314 $this->mHeaderVariant
= $this->validateVariant( $language );
315 if ( $this->mHeaderVariant
) {
321 return $this->mHeaderVariant
;
325 * Dictionary-based conversion.
326 * This function would not parse the conversion rules.
327 * If you want to parse rules, try to use convert() or
330 * @param $text String the text to be converted
331 * @param $toVariant bool|string the target language code
332 * @return String the converted text
334 public function autoConvert( $text, $toVariant = false ) {
335 wfProfileIn( __METHOD__
);
340 $toVariant = $this->getPreferredVariant();
342 wfProfileOut( __METHOD__
);
347 if( $this->guessVariant( $text, $toVariant ) ) {
348 wfProfileOut( __METHOD__
);
352 /* we convert everything except:
353 1. HTML markups (anything between < and >)
355 3. placeholders created by the parser
358 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
359 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
364 // this one is needed when the text is inside an HTML markup
365 $htmlfix = '|<[^>]+$|^[^<>]*>';
367 // disable convert to variants between <code></code> tags
368 $codefix = '<code>.+?<\/code>|';
369 // disable convertsion of <script type="text/javascript"> ... </script>
370 $scriptfix = '<script.*?>.*?<\/script>|';
371 // disable conversion of <pre xxxx> ... </pre>
372 $prefix = '<pre.*?>.*?<\/pre>|';
374 $reg = '/' . $codefix . $scriptfix . $prefix .
375 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
380 // Guard against delimiter nulls in the input
381 $text = str_replace( "\000", '', $text );
383 $markupMatches = null;
384 $elementMatches = null;
385 while ( $startPos < strlen( $text ) ) {
386 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
387 $elementPos = $markupMatches[0][1];
388 $element = $markupMatches[0][0];
390 $elementPos = strlen( $text );
394 // Queue the part before the markup for translation in a batch
395 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
397 // Advance to the next position
398 $startPos = $elementPos +
strlen( $element );
400 // Translate any alt or title attributes inside the matched element
401 if ( $element !== '' && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element,
404 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
406 foreach ( array( 'title', 'alt' ) as $attrName ) {
407 if ( !isset( $attrs[$attrName] ) ) {
410 $attr = $attrs[$attrName];
411 // Don't convert URLs
412 if ( !strpos( $attr, '://' ) ) {
413 $attr = $this->translate( $attr, $toVariant );
416 // Remove HTML tags to avoid disrupting the layout
417 $attr = preg_replace( '/<[^>]+>/', '', $attr );
418 if ( $attr !== $attrs[$attrName] ) {
419 $attrs[$attrName] = $attr;
424 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
428 $literalBlob .= $element . "\000";
431 // Do the main translation batch
432 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
434 // Put the output back together
435 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
436 $literalIter = StringUtils
::explode( "\000", $literalBlob );
438 while ( $translatedIter->valid() && $literalIter->valid() ) {
439 $output .= $translatedIter->current();
440 $output .= $literalIter->current();
441 $translatedIter->next();
442 $literalIter->next();
445 wfProfileOut( __METHOD__
);
450 * Translate a string to a variant.
451 * Doesn't parse rules or do any of that other stuff, for that use
452 * convert() or convertTo().
454 * @param $text String: text to convert
455 * @param $variant String: variant language code
456 * @return String: translated text
458 public function translate( $text, $variant ) {
459 wfProfileIn( __METHOD__
);
460 // If $text is empty or only includes spaces, do nothing
461 // Otherwise translate it
462 if ( trim( $text ) ) {
464 $text = $this->mTables
[$variant]->replace( $text );
466 wfProfileOut( __METHOD__
);
471 * Call translate() to convert text to all valid variants.
473 * @param $text String: the text to be converted
474 * @return Array: variant => converted text
476 public function autoConvertToAllVariants( $text ) {
477 wfProfileIn( __METHOD__
);
481 foreach ( $this->mVariants
as $variant ) {
482 $ret[$variant] = $this->translate( $text, $variant );
485 wfProfileOut( __METHOD__
);
490 * Convert link text to all valid variants.
491 * In the first, this function only convert text outside the
492 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
493 * titles, the text will get all converted always.
494 * So I removed this feature and deprecated the function.
496 * @param $text String: the text to be converted
497 * @return Array: variant => converted text
498 * @deprecated since 1.17 Use autoConvertToAllVariants() instead
500 public function convertLinkToAllVariants( $text ) {
501 return $this->autoConvertToAllVariants( $text );
505 * Apply manual conversion rules.
507 * @param $convRule ConverterRule Object of ConverterRule
509 protected function applyManualConv( $convRule ) {
510 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
512 // Bug 24072: $mConvRuleTitle was overwritten by other manual
513 // rule(s) not for title, this breaks the title conversion.
514 $newConvRuleTitle = $convRule->getTitle();
515 if ( $newConvRuleTitle ) {
516 // So I add an empty check for getTitle()
517 $this->mConvRuleTitle
= $newConvRuleTitle;
520 // merge/remove manual conversion rules to/from global table
521 $convTable = $convRule->getConvTable();
522 $action = $convRule->getRulesAction();
523 foreach ( $convTable as $variant => $pair ) {
524 if ( !$this->validateVariant( $variant ) ) {
528 if ( $action == 'add' ) {
529 foreach ( $pair as $from => $to ) {
530 // to ensure that $from and $to not be left blank
531 // so $this->translate() could always return a string
532 if ( $from ||
$to ) {
533 // more efficient than array_merge(), about 2.5 times.
534 $this->mTables
[$variant]->setPair( $from, $to );
537 } elseif ( $action == 'remove' ) {
538 $this->mTables
[$variant]->removeArray( $pair );
544 * Auto convert a Title object to a readable string in the
547 * @param $title Title a object of Title
548 * @return String: converted title text
550 public function convertTitle( $title ) {
551 $variant = $this->getPreferredVariant();
552 $index = $title->getNamespace();
553 if ( $index === NS_MAIN
) {
556 // first let's check if a message has given us a converted name
557 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
558 if ( $nsConvMsg->exists() ) {
559 $text = $nsConvMsg->plain();
561 // the message does not exist, try retrieve it from the current
562 // variant's namespace names.
563 $langObj = $this->mLangObj
->factory( $variant );
564 $text = $langObj->getFormattedNsText( $index );
568 $text .= $title->getText();
569 $text = $this->translate( $text, $variant );
574 * Convert text to different variants of a language. The automatic
575 * conversion is done in autoConvert(). Here we parse the text
576 * marked with -{}-, which specifies special conversions of the
577 * text that can not be accomplished in autoConvert().
579 * Syntax of the markup:
580 * -{code1:text1;code2:text2;...}- or
581 * -{flags|code1:text1;code2:text2;...}- or
582 * -{text}- in which case no conversion should take place for text
584 * @param $text String: text to be converted
585 * @return String: converted text
587 public function convert( $text ) {
588 $variant = $this->getPreferredVariant();
589 return $this->convertTo( $text, $variant );
593 * Same as convert() except a extra parameter to custom variant.
595 * @param $text String: text to be converted
596 * @param $variant String: the target variant code
597 * @return String: converted text
599 public function convertTo( $text, $variant ) {
600 global $wgDisableLangConversion;
601 if ( $wgDisableLangConversion ) {
604 return $this->recursiveConvertTopLevel( $text, $variant );
608 * Recursively convert text on the outside. Allow to use nested
609 * markups to custom rules.
611 * @param $text String: text to be converted
612 * @param $variant String: the target variant code
613 * @param $depth Integer: depth of recursion
614 * @return String: converted text
616 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
619 $length = strlen( $text );
620 $shouldConvert = !$this->guessVariant( $text, $variant );
622 while ( $startPos < $length ) {
623 $pos = strpos( $text, '-{', $startPos );
625 if ( $pos === false ) {
626 // No more markup, append final segment
627 $fragment = substr( $text, $startPos );
628 $out .= $shouldConvert?
$this->autoConvert( $fragment, $variant ): $fragment;
633 // Append initial segment
634 $fragment = substr( $text, $startPos, $pos - $startPos );
635 $out .= $shouldConvert?
$this->autoConvert( $fragment, $variant ): $fragment;
640 // Do recursive conversion
641 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
648 * Recursively convert text on the inside.
650 * @param $text String: text to be converted
651 * @param $variant String: the target variant code
652 * @param $startPos int
653 * @param $depth Integer: depth of recursion
655 * @throws MWException
656 * @return String: converted text
658 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
659 // Quick sanity check (no function calls)
660 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
661 throw new MWException( __METHOD__
. ': invalid input string' );
666 $warningDone = false;
667 $length = strlen( $text );
669 while ( $startPos < $length ) {
671 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
681 // Append initial segment
682 $inner .= substr( $text, $startPos, $pos - $startPos );
690 if ( $depth >= $this->mMaxDepth
) {
692 if ( !$warningDone ) {
693 $inner .= '<span class="error">' .
694 wfMessage( 'language-converter-depth-warning' )
695 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
702 // Recursively parse another rule
703 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
708 $rule = new ConverterRule( $inner, $this );
709 $rule->parse( $variant );
710 $this->applyManualConv( $rule );
711 return $rule->getDisplay();
713 throw new MWException( __METHOD__
. ': invalid regex match' );
718 if ( $startPos < $length ) {
719 $inner .= substr( $text, $startPos );
722 return '-{' . $this->autoConvert( $inner, $variant );
726 * If a language supports multiple variants, it is possible that
727 * non-existing link in one variant actually exists in another variant.
728 * This function tries to find it. See e.g. LanguageZh.php
730 * @param $link String: the name of the link
731 * @param $nt Mixed: the title object of the link
732 * @param $ignoreOtherCond Boolean: to disable other conditions when
733 * we need to transclude a template or update a category's link
734 * @return Null, the input parameters may be modified upon return
736 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
737 # If the article has already existed, there is no need to
738 # check it again, otherwise it may cause a fault.
739 if ( is_object( $nt ) && $nt->exists() ) {
743 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
745 $isredir = $wgRequest->getText( 'redirect', 'yes' );
746 $action = $wgRequest->getText( 'action' );
747 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
748 $disableLinkConversion = $wgDisableLangConversion
749 ||
$wgDisableTitleConversion;
750 $linkBatch = new LinkBatch();
754 if ( $disableLinkConversion ||
755 ( !$ignoreOtherCond &&
758 ||
$action == 'submit'
759 ||
$linkconvert == 'no'
760 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
764 if ( is_object( $nt ) ) {
765 $ns = $nt->getNamespace();
768 $variants = $this->autoConvertToAllVariants( $link );
769 if ( !$variants ) { // give up
775 foreach ( $variants as $v ) {
777 $varnt = Title
::newFromText( $v, $ns );
778 if ( !is_null( $varnt ) ) {
779 $linkBatch->addObj( $varnt );
785 // fetch all variants in single query
786 $linkBatch->execute();
788 foreach ( $titles as $varnt ) {
789 if ( $varnt->getArticleID() > 0 ) {
791 $link = $varnt->getText();
798 * Returns language specific hash options.
802 public function getExtraHashOptions() {
803 $variant = $this->getPreferredVariant();
804 return '!' . $variant;
808 * Guess if a text is written in a variant. This should be implemented in subclasses.
810 * @param string $text the text to be checked
811 * @param string $variant language code of the variant to be checked for
812 * @return bool true if $text appears to be written in $variant, false if not
814 * @author Nikola Smolenski <smolensk@eunet.rs>
817 public function guessVariant($text, $variant) {
822 * Load default conversion tables.
823 * This method must be implemented in derived class.
826 * @throws MWException
828 function loadDefaultTables() {
829 $name = get_class( $this );
830 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
834 * Load conversion tables either from the cache or the disk.
836 * @param $fromCache Boolean: load from memcached? Defaults to true.
838 function loadTables( $fromCache = true ) {
839 global $wgLangConvMemc;
841 if ( $this->mTablesLoaded
) {
845 wfProfileIn( __METHOD__
);
846 $this->mTablesLoaded
= true;
847 $this->mTables
= false;
849 wfProfileIn( __METHOD__
. '-cache' );
850 $this->mTables
= $wgLangConvMemc->get( $this->mCacheKey
);
851 wfProfileOut( __METHOD__
. '-cache' );
854 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
855 wfProfileIn( __METHOD__
. '-recache' );
856 // not in cache, or we need a fresh reload.
857 // We will first load the default tables
858 // then update them using things in MediaWiki:Conversiontable/*
859 $this->loadDefaultTables();
860 foreach ( $this->mVariants
as $var ) {
861 $cached = $this->parseCachedTable( $var );
862 $this->mTables
[$var]->mergeArray( $cached );
865 $this->postLoadTables();
866 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
868 $wgLangConvMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
869 wfProfileOut( __METHOD__
. '-recache' );
871 wfProfileOut( __METHOD__
);
875 * Hook for post processing after conversion tables are loaded.
877 function postLoadTables() { }
880 * Reload the conversion tables.
884 function reloadTables() {
885 if ( $this->mTables
) {
886 unset( $this->mTables
);
888 $this->mTablesLoaded
= false;
889 $this->loadTables( false );
893 * Parse the conversion table stored in the cache.
895 * The tables should be in blocks of the following form:
902 * To make the tables more manageable, subpages are allowed
903 * and will be parsed recursively if $recursive == true.
905 * @param $code String: language code
906 * @param $subpage String: subpage name
907 * @param $recursive Boolean: parse subpages recursively? Defaults to true.
911 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
912 static $parsed = array();
914 $key = 'Conversiontable/' . $code;
916 $key .= '/' . $subpage;
918 if ( array_key_exists( $key, $parsed ) ) {
922 $parsed[$key] = true;
924 if ( $subpage === '' ) {
925 $txt = MessageCache
::singleton()->get( 'conversiontable', true, $code );
928 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
929 if ( $title && $title->exists() ) {
930 $revision = Revision
::newFromTitle( $title );
932 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
933 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
936 //@todo: in the future, use a specialized content model, perhaps based on json!
941 # Nothing to parse if there's no text
942 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
946 // get all subpage links of the form
947 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
948 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
950 $subs = StringUtils
::explode( '[[', $txt );
952 foreach ( $subs as $sub ) {
953 $link = explode( ']]', $sub, 2 );
954 if ( count( $link ) != 2 ) {
957 $b = explode( '|', $link[0], 2 );
958 $b = explode( '/', trim( $b[0] ), 3 );
959 if ( count( $b ) == 3 ) {
965 if ( $b[0] == $linkhead && $b[1] == $code ) {
966 $sublinks[] = $sublink;
970 // parse the mappings in this page
971 $blocks = StringUtils
::explode( '-{', $txt );
974 foreach ( $blocks as $block ) {
976 // Skip the part before the first -{
980 $mappings = explode( '}-', $block, 2 );
981 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
983 $table = StringUtils
::explode( ';', $stripped );
984 foreach ( $table as $t ) {
985 $m = explode( '=>', $t, 3 );
986 if ( count( $m ) != 2 ) {
989 // trim any trailling comments starting with '//'
990 $tt = explode( '//', $m[1], 2 );
991 $ret[trim( $m[0] )] = trim( $tt[0] );
995 // recursively parse the subpages
997 foreach ( $sublinks as $link ) {
998 $s = $this->parseCachedTable( $code, $link, $recursive );
999 $ret = array_merge( $ret, $s );
1003 if ( $this->mUcfirst
) {
1004 foreach ( $ret as $k => $v ) {
1005 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1012 * Enclose a string with the "no conversion" tag. This is used by
1013 * various functions in the Parser.
1015 * @param $text String: text to be tagged for no conversion
1016 * @param $noParse Boolean: unused
1017 * @return String: the tagged text
1019 public function markNoConversion( $text, $noParse = false ) {
1020 # don't mark if already marked
1021 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1025 $ret = "-{R|$text}-";
1030 * Convert the sorting key for category links. This should make different
1031 * keys that are variants of each other map to the same key.
1033 * @param $key string
1037 function convertCategoryKey( $key ) {
1042 * Hook to refresh the cache of conversion tables when
1043 * MediaWiki:Conversiontable* is updated.
1046 * @param $page WikiPage object
1047 * @param $user Object: User object for the current user
1048 * @param $content Content: new page content
1049 * @param $summary String: edit summary of the edit
1050 * @param $isMinor Boolean: was the edit marked as minor?
1051 * @param $isWatch Boolean: did the user watch this page or not?
1053 * @param $flags int Bitfield
1054 * @param $revision Object: new Revision object or null
1055 * @return Boolean: true
1057 function OnArticleContentSaveComplete( $page, $user, $content, $summary, $isMinor,
1058 $isWatch, $section, $flags, $revision ) {
1059 $titleobj = $page->getTitle();
1060 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1061 $title = $titleobj->getDBkey();
1062 $t = explode( '/', $title, 3 );
1064 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1065 if ( $this->validateVariant( $t[1] ) ) {
1066 $this->reloadTables();
1074 * Armour rendered math against conversion.
1075 * Escape special chars in parsed math text. (in most cases are img elements)
1077 * @param $text String: text to armour against conversion
1078 * @return String: armoured text where { and } have been converted to
1081 public function armourMath( $text ) {
1082 // convert '-{' and '}-' to '-{' and '}-' to prevent
1083 // any unwanted markup appearing in the math image tag.
1084 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
1089 * Get the cached separator pattern for ConverterRule::parseRules()
1091 function getVarSeparatorPattern() {
1092 if ( is_null( $this->mVarSeparatorPattern
) ) {
1093 // varsep_pattern for preg_split:
1094 // text should be splited by ";" only if a valid variant
1095 // name exist after the markup, for example:
1096 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1097 // <span style="font-size:120%;">yyy</span>;}-
1098 // we should split it as:
1100 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1101 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1105 foreach ( $this->mVariants
as $variant ) {
1106 // zh-hans:xxx;zh-hant:yyy
1107 $pat .= $variant . '\s*:|';
1108 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1109 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1112 $this->mVarSeparatorPattern
= $pat;
1114 return $this->mVarSeparatorPattern
;
1119 * Parser for rules of language conversion , parse rules in -{ }- tag.
1121 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1123 class ConverterRule
{
1124 public $mText; // original text in -{text}-
1125 public $mConverter; // LanguageConverter object
1126 public $mRuleDisplay = '';
1127 public $mRuleTitle = false;
1128 public $mRules = '';// string : the text of the rules
1129 public $mRulesAction = 'none';
1130 public $mFlags = array();
1131 public $mVariantFlags = array();
1132 public $mConvTable = array();
1133 public $mBidtable = array();// array of the translation in each variant
1134 public $mUnidtable = array();// array of the translation in each variant
1139 * @param $text String: the text between -{ and }-
1140 * @param $converter LanguageConverter object
1142 public function __construct( $text, $converter ) {
1143 $this->mText
= $text;
1144 $this->mConverter
= $converter;
1148 * Check if variants array in convert array.
1150 * @param $variants Array or string: variant language code
1151 * @return String: translated text
1153 public function getTextInBidtable( $variants ) {
1154 $variants = (array)$variants;
1158 foreach ( $variants as $variant ) {
1159 if ( isset( $this->mBidtable
[$variant] ) ) {
1160 return $this->mBidtable
[$variant];
1167 * Parse flags with syntax -{FLAG| ... }-
1170 function parseFlags() {
1171 $text = $this->mText
;
1173 $variantFlags = array();
1175 $sepPos = strpos( $text, '|' );
1176 if ( $sepPos !== false ) {
1177 $validFlags = $this->mConverter
->mFlags
;
1178 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1179 foreach ( $f as $ff ) {
1181 if ( isset( $validFlags[$ff] ) ) {
1182 $flags[$validFlags[$ff]] = true;
1185 $text = strval( substr( $text, $sepPos +
1 ) );
1190 } elseif ( isset( $flags['R'] ) ) {
1191 $flags = array( 'R' => true );// remove other flags
1192 } elseif ( isset( $flags['N'] ) ) {
1193 $flags = array( 'N' => true );// remove other flags
1194 } elseif ( isset( $flags['-'] ) ) {
1195 $flags = array( '-' => true );// remove other flags
1196 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1198 } elseif ( isset( $flags['H'] ) ) {
1199 // replace A flag, and remove other flags except T
1200 $temp = array( '+' => true, 'H' => true );
1201 if ( isset( $flags['T'] ) ) {
1204 if ( isset( $flags['D'] ) ) {
1209 if ( isset( $flags['A'] ) ) {
1213 if ( isset( $flags['D'] ) ) {
1214 unset( $flags['S'] );
1216 // try to find flags like "zh-hans", "zh-hant"
1217 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1218 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1219 if ( $variantFlags ) {
1220 $variantFlags = array_flip( $variantFlags );
1224 $this->mVariantFlags
= $variantFlags;
1225 $this->mRules
= $text;
1226 $this->mFlags
= $flags;
1230 * Generate conversion table.
1233 function parseRules() {
1234 $rules = $this->mRules
;
1235 $bidtable = array();
1236 $unidtable = array();
1237 $variants = $this->mConverter
->mVariants
;
1238 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1240 $choice = preg_split( $varsep_pattern, $rules );
1242 foreach ( $choice as $c ) {
1243 $v = explode( ':', $c, 2 );
1244 if ( count( $v ) != 2 ) {
1245 // syntax error, skip
1248 $to = trim( $v[1] );
1250 $u = explode( '=>', $v, 2 );
1251 // if $to is empty, strtr() could return a wrong result
1252 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1253 $bidtable[$v] = $to;
1254 } elseif ( count( $u ) == 2 ) {
1255 $from = trim( $u[0] );
1257 if ( array_key_exists( $v, $unidtable )
1258 && !is_array( $unidtable[$v] )
1260 && in_array( $v, $variants ) ) {
1261 $unidtable[$v] = array( $from => $to );
1262 } elseif ( $to && in_array( $v, $variants ) ) {
1263 $unidtable[$v][$from] = $to;
1266 // syntax error, pass
1267 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1268 $bidtable = array();
1269 $unidtable = array();
1273 $this->mBidtable
= $bidtable;
1274 $this->mUnidtable
= $unidtable;
1282 function getRulesDesc() {
1283 $codesep = $this->mConverter
->mDescCodeSep
;
1284 $varsep = $this->mConverter
->mDescVarSep
;
1286 foreach ( $this->mBidtable
as $k => $v ) {
1287 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1289 foreach ( $this->mUnidtable
as $k => $a ) {
1290 foreach ( $a as $from => $to ) {
1291 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1292 "$codesep$to$varsep";
1299 * Parse rules conversion.
1306 function getRuleConvertedStr( $variant ) {
1307 $bidtable = $this->mBidtable
;
1308 $unidtable = $this->mUnidtable
;
1310 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1311 return $this->mRules
;
1313 // display current variant in bidirectional array
1314 $disp = $this->getTextInBidtable( $variant );
1315 // or display current variant in fallbacks
1317 $disp = $this->getTextInBidtable(
1318 $this->mConverter
->getVariantFallbacks( $variant ) );
1320 // or display current variant in unidirectional array
1321 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1322 $disp = array_values( $unidtable[$variant] );
1325 // or display frist text under disable manual convert
1327 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1328 if ( count( $bidtable ) > 0 ) {
1329 $disp = array_values( $bidtable );
1332 $disp = array_values( $unidtable );
1333 $disp = array_values( $disp[0] );
1342 * Generate conversion table for all text.
1345 function generateConvTable() {
1346 // Special case optimisation
1347 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1348 $this->mConvTable
= array();
1352 $bidtable = $this->mBidtable
;
1353 $unidtable = $this->mUnidtable
;
1354 $manLevel = $this->mConverter
->mManualLevel
;
1357 foreach ( $this->mConverter
->mVariants
as $v ) {
1358 /* for bidirectional array
1359 fill in the missing variants, if any,
1361 if ( !isset( $bidtable[$v] ) ) {
1363 $this->mConverter
->getVariantFallbacks( $v );
1364 $vf = $this->getTextInBidtable( $variantFallbacks );
1366 $bidtable[$v] = $vf;
1370 if ( isset( $bidtable[$v] ) ) {
1371 foreach ( $vmarked as $vo ) {
1372 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1373 // or -{H|zh:WordZh;zh-tw:WordTw}-
1374 // or -{-|zh:WordZh;zh-tw:WordTw}-
1375 // to introduce a custom mapping between
1376 // words WordZh and WordTw in the whole text
1377 if ( $manLevel[$v] == 'bidirectional' ) {
1378 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1380 if ( $manLevel[$vo] == 'bidirectional' ) {
1381 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1386 /* for unidirectional array fill to convert tables */
1387 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1388 && isset( $unidtable[$v] ) )
1390 if ( isset( $this->mConvTable
[$v] ) ) {
1391 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1393 $this->mConvTable
[$v] = $unidtable[$v];
1400 * Parse rules and flags.
1401 * @param $variant String: variant language code
1403 public function parse( $variant = null ) {
1405 $variant = $this->mConverter
->getPreferredVariant();
1408 $this->parseFlags();
1409 $flags = $this->mFlags
;
1411 // convert to specified variant
1412 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1413 if ( $this->mVariantFlags
) {
1414 // check if current variant in flags
1415 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1416 // then convert <text to convert> to current language
1417 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1419 } else { // if current variant no in flags,
1420 // then we check its fallback variants.
1422 $this->mConverter
->getVariantFallbacks( $variant );
1423 if( is_array( $variantFallbacks ) ) {
1424 foreach ( $variantFallbacks as $variantFallback ) {
1425 // if current variant's fallback exist in flags
1426 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1427 // then convert <text to convert> to fallback language
1429 $this->mConverter
->autoConvert( $this->mRules
,
1436 $this->mFlags
= $flags = array( 'R' => true );
1439 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1440 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1441 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1442 $this->parseRules();
1444 $rules = $this->mRules
;
1446 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1447 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1448 // fill all variants if text in -{A/H/-|text} without rules
1449 foreach ( $this->mConverter
->mVariants
as $v ) {
1450 $this->mBidtable
[$v] = $rules;
1452 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1453 $this->mFlags
= $flags = array( 'R' => true );
1457 $this->mRuleDisplay
= false;
1458 foreach ( $flags as $flag => $unused ) {
1461 // if we don't do content convert, still strip the -{}- tags
1462 $this->mRuleDisplay
= $rules;
1465 // process N flag: output current variant name
1466 $ruleVar = trim( $rules );
1467 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1468 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1470 $this->mRuleDisplay
= '';
1474 // process D flag: output rules description
1475 $this->mRuleDisplay
= $this->getRulesDesc();
1478 // process H,- flag or T only: output nothing
1479 $this->mRuleDisplay
= '';
1482 $this->mRulesAction
= 'remove';
1483 $this->mRuleDisplay
= '';
1486 $this->mRulesAction
= 'add';
1487 $this->mRuleDisplay
= '';
1490 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1493 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1494 $this->mRuleDisplay
= '';
1497 // ignore unknown flags (but see error case below)
1500 if ( $this->mRuleDisplay
=== false ) {
1501 $this->mRuleDisplay
= '<span class="error">'
1502 . wfMessage( 'converter-manual-rule-error' )->inContentLanguage()->escaped()
1506 $this->generateConvTable();
1510 * @todo FIXME: code this function :)
1512 public function hasRules() {
1517 * Get display text on markup -{...}-
1520 public function getDisplay() {
1521 return $this->mRuleDisplay
;
1525 * Get converted title.
1528 public function getTitle() {
1529 return $this->mRuleTitle
;
1533 * Return how deal with conversion rules.
1536 public function getRulesAction() {
1537 return $this->mRulesAction
;
1541 * Get conversion table. (bidirectional and unidirectional
1545 public function getConvTable() {
1546 return $this->mConvTable
;
1550 * Get conversion rules string.
1553 public function getRules() {
1554 return $this->mRules
;
1558 * Get conversion flags.
1561 public function getFlags() {
1562 return $this->mFlags
;