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 var $mMainLanguageCode;
51 var $mVariants, $mVariantFallbacks, $mVariantNames;
52 var $mTablesLoaded = false;
54 // 'bidirectional' 'unidirectional' 'disable' for each variant
58 * @var String: memcached key name
64 var $mDescCodeSep = ':', $mDescVarSep = ';';
65 var $mUcfirst = false;
66 var $mConvRuleTitle = false;
71 var $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 or headers
188 * @return String: the default variant code
190 public function getDefaultVariant() {
191 global $wgDefaultLanguageVariant;
193 $req = $this->getURLVariant();
195 if ( $wgDefaultLanguageVariant && !$req ) {
196 $req = $this->validateVariant( $wgDefaultLanguageVariant );
202 return $this->mMainLanguageCode
;
206 * Validate the variant
207 * @param $variant String: the variant to validate
208 * @return Mixed: returns the variant if it is valid, null otherwise
210 public function validateVariant( $variant = null ) {
211 if ( $variant !== null && in_array( $variant, $this->mVariants
) ) {
218 * Get the variant specified in the URL
220 * @return Mixed: variant if one found, false otherwise.
222 public function getURLVariant() {
225 if ( $this->mURLVariant
) {
226 return $this->mURLVariant
;
229 // see if the preference is set in the request
230 $ret = $wgRequest->getText( 'variant' );
233 $ret = $wgRequest->getVal( 'uselang' );
236 return $this->mURLVariant
= $this->validateVariant( $ret );
240 * Determine if the user has a variant set.
242 * @return Mixed: variant if one found, false otherwise.
244 protected function getUserVariant() {
247 // memoizing this function wreaks havoc on parserTest.php
249 if ( $this->mUserVariant ) {
250 return $this->mUserVariant;
254 // Get language variant preference from logged in users
255 // Don't call this on stub objects because that causes infinite
256 // recursion during initialisation
257 if ( $wgUser->isLoggedIn() ) {
258 $ret = $wgUser->getOption( 'variant' );
260 // figure out user lang without constructing wgLang to avoid
261 // infinite recursion
262 $ret = $wgUser->getOption( 'language' );
265 return $this->mUserVariant
= $this->validateVariant( $ret );
269 * Determine the language variant from the Accept-Language header.
271 * @return Mixed: variant if one found, false otherwise.
273 protected function getHeaderVariant() {
276 if ( $this->mHeaderVariant
) {
277 return $this->mHeaderVariant
;
280 // see if some supported language variant is set in the
282 $languages = array_keys( $wgRequest->getAcceptLang() );
283 if ( empty( $languages ) ) {
287 $fallbackLanguages = array();
288 foreach ( $languages as $language ) {
289 $this->mHeaderVariant
= $this->validateVariant( $language );
290 if ( $this->mHeaderVariant
) {
294 // To see if there are fallbacks of current language.
295 // We record these fallback variants, and process
297 $fallbacks = $this->getVariantFallbacks( $language );
298 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode
) {
299 $fallbackLanguages[] = $fallbacks;
300 } elseif ( is_array( $fallbacks ) ) {
302 array_merge( $fallbackLanguages, $fallbacks );
306 if ( !$this->mHeaderVariant
) {
307 // process fallback languages now
308 $fallback_languages = array_unique( $fallbackLanguages );
309 foreach ( $fallback_languages as $language ) {
310 $this->mHeaderVariant
= $this->validateVariant( $language );
311 if ( $this->mHeaderVariant
) {
317 return $this->mHeaderVariant
;
321 * Dictionary-based conversion.
322 * This function would not parse the conversion rules.
323 * If you want to parse rules, try to use convert() or
326 * @param $text String the text to be converted
327 * @param $toVariant bool|string the target language code
328 * @return String the converted text
330 public function autoConvert( $text, $toVariant = false ) {
331 wfProfileIn( __METHOD__
);
336 $toVariant = $this->getPreferredVariant();
338 wfProfileOut( __METHOD__
);
343 if( $this->guessVariant( $text, $toVariant ) ) {
344 wfProfileOut( __METHOD__
);
348 /* we convert everything except:
349 1. HTML markups (anything between < and >)
351 3. placeholders created by the parser
354 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
355 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
360 // this one is needed when the text is inside an HTML markup
361 $htmlfix = '|<[^>]+$|^[^<>]*>';
363 // disable convert to variants between <code></code> tags
364 $codefix = '<code>.+?<\/code>|';
365 // disable convertsion of <script type="text/javascript"> ... </script>
366 $scriptfix = '<script.*?>.*?<\/script>|';
367 // disable conversion of <pre xxxx> ... </pre>
368 $prefix = '<pre.*?>.*?<\/pre>|';
370 $reg = '/' . $codefix . $scriptfix . $prefix .
371 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
376 // Guard against delimiter nulls in the input
377 $text = str_replace( "\000", '', $text );
379 $markupMatches = null;
380 $elementMatches = null;
381 while ( $startPos < strlen( $text ) ) {
382 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
383 $elementPos = $markupMatches[0][1];
384 $element = $markupMatches[0][0];
386 $elementPos = strlen( $text );
390 // Queue the part before the markup for translation in a batch
391 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
393 // Advance to the next position
394 $startPos = $elementPos +
strlen( $element );
396 // Translate any alt or title attributes inside the matched element
397 if ( $element !== '' && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element,
400 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
402 foreach ( array( 'title', 'alt' ) as $attrName ) {
403 if ( !isset( $attrs[$attrName] ) ) {
406 $attr = $attrs[$attrName];
407 // Don't convert URLs
408 if ( !strpos( $attr, '://' ) ) {
409 $attr = $this->translate( $attr, $toVariant );
412 // Remove HTML tags to avoid disrupting the layout
413 $attr = preg_replace( '/<[^>]+>/', '', $attr );
414 if ( $attr !== $attrs[$attrName] ) {
415 $attrs[$attrName] = $attr;
420 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
424 $literalBlob .= $element . "\000";
427 // Do the main translation batch
428 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
430 // Put the output back together
431 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
432 $literalIter = StringUtils
::explode( "\000", $literalBlob );
434 while ( $translatedIter->valid() && $literalIter->valid() ) {
435 $output .= $translatedIter->current();
436 $output .= $literalIter->current();
437 $translatedIter->next();
438 $literalIter->next();
441 wfProfileOut( __METHOD__
);
446 * Translate a string to a variant.
447 * Doesn't parse rules or do any of that other stuff, for that use
448 * convert() or convertTo().
450 * @param $text String: text to convert
451 * @param $variant String: variant language code
452 * @return String: translated text
454 public function translate( $text, $variant ) {
455 wfProfileIn( __METHOD__
);
456 // If $text is empty or only includes spaces, do nothing
457 // Otherwise translate it
458 if ( trim( $text ) ) {
460 $text = $this->mTables
[$variant]->replace( $text );
462 wfProfileOut( __METHOD__
);
467 * Call translate() to convert text to all valid variants.
469 * @param $text String: the text to be converted
470 * @return Array: variant => converted text
472 public function autoConvertToAllVariants( $text ) {
473 wfProfileIn( __METHOD__
);
477 foreach ( $this->mVariants
as $variant ) {
478 $ret[$variant] = $this->translate( $text, $variant );
481 wfProfileOut( __METHOD__
);
486 * Convert link text to all valid variants.
487 * In the first, this function only convert text outside the
488 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
489 * titles, the text will get all converted always.
490 * So I removed this feature and deprecated the function.
492 * @param $text String: the text to be converted
493 * @return Array: variant => converted text
494 * @deprecated since 1.17 Use autoConvertToAllVariants() instead
496 public function convertLinkToAllVariants( $text ) {
497 return $this->autoConvertToAllVariants( $text );
501 * Apply manual conversion rules.
503 * @param $convRule ConverterRule Object of ConverterRule
505 protected function applyManualConv( $convRule ) {
506 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
508 // Bug 24072: $mConvRuleTitle was overwritten by other manual
509 // rule(s) not for title, this breaks the title conversion.
510 $newConvRuleTitle = $convRule->getTitle();
511 if ( $newConvRuleTitle ) {
512 // So I add an empty check for getTitle()
513 $this->mConvRuleTitle
= $newConvRuleTitle;
516 // merge/remove manual conversion rules to/from global table
517 $convTable = $convRule->getConvTable();
518 $action = $convRule->getRulesAction();
519 foreach ( $convTable as $variant => $pair ) {
520 if ( !$this->validateVariant( $variant ) ) {
524 if ( $action == 'add' ) {
525 foreach ( $pair as $from => $to ) {
526 // to ensure that $from and $to not be left blank
527 // so $this->translate() could always return a string
528 if ( $from ||
$to ) {
529 // more efficient than array_merge(), about 2.5 times.
530 $this->mTables
[$variant]->setPair( $from, $to );
533 } elseif ( $action == 'remove' ) {
534 $this->mTables
[$variant]->removeArray( $pair );
540 * Auto convert a Title object to a readable string in the
543 * @param $title Title a object of Title
544 * @return String: converted title text
546 public function convertTitle( $title ) {
547 $variant = $this->getPreferredVariant();
548 $index = $title->getNamespace();
549 if ( $index === NS_MAIN
) {
552 // first let's check if a message has given us a converted name
553 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
554 if ( $nsConvMsg->exists() ) {
555 $text = $nsConvMsg->plain();
557 // the message does not exist, try retrieve it from the current
558 // variant's namespace names.
559 $langObj = $this->mLangObj
->factory( $variant );
560 $text = $langObj->getFormattedNsText( $index );
564 $text .= $title->getText();
565 $text = $this->translate( $text, $variant );
570 * Convert text to different variants of a language. The automatic
571 * conversion is done in autoConvert(). Here we parse the text
572 * marked with -{}-, which specifies special conversions of the
573 * text that can not be accomplished in autoConvert().
575 * Syntax of the markup:
576 * -{code1:text1;code2:text2;...}- or
577 * -{flags|code1:text1;code2:text2;...}- or
578 * -{text}- in which case no conversion should take place for text
580 * @param $text String: text to be converted
581 * @return String: converted text
583 public function convert( $text ) {
584 $variant = $this->getPreferredVariant();
585 return $this->convertTo( $text, $variant );
589 * Same as convert() except a extra parameter to custom variant.
591 * @param $text String: text to be converted
592 * @param $variant String: the target variant code
593 * @return String: converted text
595 public function convertTo( $text, $variant ) {
596 global $wgDisableLangConversion;
597 if ( $wgDisableLangConversion ) {
600 return $this->recursiveConvertTopLevel( $text, $variant );
604 * Recursively convert text on the outside. Allow to use nested
605 * markups to custom rules.
607 * @param $text String: text to be converted
608 * @param $variant String: the target variant code
609 * @param $depth Integer: depth of recursion
610 * @return String: converted text
612 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
615 $length = strlen( $text );
616 $shouldConvert = !$this->guessVariant( $text, $variant );
618 while ( $startPos < $length ) {
619 $pos = strpos( $text, '-{', $startPos );
621 if ( $pos === false ) {
622 // No more markup, append final segment
623 $fragment = substr( $text, $startPos );
624 $out .= $shouldConvert?
$this->autoConvert( $fragment, $variant ): $fragment;
629 // Append initial segment
630 $fragment = substr( $text, $startPos, $pos - $startPos );
631 $out .= $shouldConvert?
$this->autoConvert( $fragment, $variant ): $fragment;
636 // Do recursive conversion
637 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
644 * Recursively convert text on the inside.
646 * @param $text String: text to be converted
647 * @param $variant String: the target variant code
648 * @param $startPos int
649 * @param $depth Integer: depth of recursion
651 * @throws MWException
652 * @return String: converted text
654 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
655 // Quick sanity check (no function calls)
656 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
657 throw new MWException( __METHOD__
. ': invalid input string' );
662 $warningDone = false;
663 $length = strlen( $text );
665 while ( $startPos < $length ) {
667 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
677 // Append initial segment
678 $inner .= substr( $text, $startPos, $pos - $startPos );
686 if ( $depth >= $this->mMaxDepth
) {
688 if ( !$warningDone ) {
689 $inner .= '<span class="error">' .
690 wfMessage( 'language-converter-depth-warning' )
691 ->numParams( $this->mMaxDepth
)->inContentLanguage()->text() .
698 // Recursively parse another rule
699 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
704 $rule = new ConverterRule( $inner, $this );
705 $rule->parse( $variant );
706 $this->applyManualConv( $rule );
707 return $rule->getDisplay();
709 throw new MWException( __METHOD__
. ': invalid regex match' );
714 if ( $startPos < $length ) {
715 $inner .= substr( $text, $startPos );
718 return '-{' . $this->autoConvert( $inner, $variant );
722 * If a language supports multiple variants, it is possible that
723 * non-existing link in one variant actually exists in another variant.
724 * This function tries to find it. See e.g. LanguageZh.php
726 * @param $link String: the name of the link
727 * @param $nt Mixed: the title object of the link
728 * @param $ignoreOtherCond Boolean: to disable other conditions when
729 * we need to transclude a template or update a category's link
730 * @return Null, the input parameters may be modified upon return
732 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
733 # If the article has already existed, there is no need to
734 # check it again, otherwise it may cause a fault.
735 if ( is_object( $nt ) && $nt->exists() ) {
739 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
741 $isredir = $wgRequest->getText( 'redirect', 'yes' );
742 $action = $wgRequest->getText( 'action' );
743 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
744 $disableLinkConversion = $wgDisableLangConversion
745 ||
$wgDisableTitleConversion;
746 $linkBatch = new LinkBatch();
750 if ( $disableLinkConversion ||
751 ( !$ignoreOtherCond &&
754 ||
$action == 'submit'
755 ||
$linkconvert == 'no'
756 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
760 if ( is_object( $nt ) ) {
761 $ns = $nt->getNamespace();
764 $variants = $this->autoConvertToAllVariants( $link );
765 if ( !$variants ) { // give up
771 foreach ( $variants as $v ) {
773 $varnt = Title
::newFromText( $v, $ns );
774 if ( !is_null( $varnt ) ) {
775 $linkBatch->addObj( $varnt );
781 // fetch all variants in single query
782 $linkBatch->execute();
784 foreach ( $titles as $varnt ) {
785 if ( $varnt->getArticleID() > 0 ) {
787 $link = $varnt->getText();
794 * Returns language specific hash options.
798 public function getExtraHashOptions() {
799 $variant = $this->getPreferredVariant();
800 return '!' . $variant;
804 * Guess if a text is written in a variant. This should be implemented in subclasses.
806 * @param string $text the text to be checked
807 * @param string $variant language code of the variant to be checked for
808 * @return bool true if $text appears to be written in $variant, false if not
810 * @author Nikola Smolenski <smolensk@eunet.rs>
813 public function guessVariant($text, $variant) {
818 * Load default conversion tables.
819 * This method must be implemented in derived class.
822 * @throws MWException
824 function loadDefaultTables() {
825 $name = get_class( $this );
826 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
830 * Load conversion tables either from the cache or the disk.
832 * @param $fromCache Boolean: load from memcached? Defaults to true.
834 function loadTables( $fromCache = true ) {
835 global $wgLangConvMemc;
837 if ( $this->mTablesLoaded
) {
841 wfProfileIn( __METHOD__
);
842 $this->mTablesLoaded
= true;
843 $this->mTables
= false;
845 wfProfileIn( __METHOD__
. '-cache' );
846 $this->mTables
= $wgLangConvMemc->get( $this->mCacheKey
);
847 wfProfileOut( __METHOD__
. '-cache' );
850 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
851 wfProfileIn( __METHOD__
. '-recache' );
852 // not in cache, or we need a fresh reload.
853 // We will first load the default tables
854 // then update them using things in MediaWiki:Conversiontable/*
855 $this->loadDefaultTables();
856 foreach ( $this->mVariants
as $var ) {
857 $cached = $this->parseCachedTable( $var );
858 $this->mTables
[$var]->mergeArray( $cached );
861 $this->postLoadTables();
862 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
864 $wgLangConvMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
865 wfProfileOut( __METHOD__
. '-recache' );
867 wfProfileOut( __METHOD__
);
871 * Hook for post processing after conversion tables are loaded.
873 function postLoadTables() { }
876 * Reload the conversion tables.
880 function reloadTables() {
881 if ( $this->mTables
) {
882 unset( $this->mTables
);
884 $this->mTablesLoaded
= false;
885 $this->loadTables( false );
889 * Parse the conversion table stored in the cache.
891 * The tables should be in blocks of the following form:
898 * To make the tables more manageable, subpages are allowed
899 * and will be parsed recursively if $recursive == true.
901 * @param $code String: language code
902 * @param $subpage String: subpage name
903 * @param $recursive Boolean: parse subpages recursively? Defaults to true.
907 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
908 static $parsed = array();
910 $key = 'Conversiontable/' . $code;
912 $key .= '/' . $subpage;
914 if ( array_key_exists( $key, $parsed ) ) {
918 $parsed[$key] = true;
920 if ( $subpage === '' ) {
921 $txt = MessageCache
::singleton()->get( 'conversiontable', true, $code );
924 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
925 if ( $title && $title->exists() ) {
926 $revision = Revision
::newFromTitle( $title );
928 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT
) {
929 $txt = $revision->getContent( Revision
::RAW
)->getNativeData();
932 //@todo: in the future, use a specialized content model, perhaps based on json!
937 # Nothing to parse if there's no text
938 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
942 // get all subpage links of the form
943 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
944 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
946 $subs = StringUtils
::explode( '[[', $txt );
948 foreach ( $subs as $sub ) {
949 $link = explode( ']]', $sub, 2 );
950 if ( count( $link ) != 2 ) {
953 $b = explode( '|', $link[0], 2 );
954 $b = explode( '/', trim( $b[0] ), 3 );
955 if ( count( $b ) == 3 ) {
961 if ( $b[0] == $linkhead && $b[1] == $code ) {
962 $sublinks[] = $sublink;
966 // parse the mappings in this page
967 $blocks = StringUtils
::explode( '-{', $txt );
970 foreach ( $blocks as $block ) {
972 // Skip the part before the first -{
976 $mappings = explode( '}-', $block, 2 );
977 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
979 $table = StringUtils
::explode( ';', $stripped );
980 foreach ( $table as $t ) {
981 $m = explode( '=>', $t, 3 );
982 if ( count( $m ) != 2 ) {
985 // trim any trailling comments starting with '//'
986 $tt = explode( '//', $m[1], 2 );
987 $ret[trim( $m[0] )] = trim( $tt[0] );
991 // recursively parse the subpages
993 foreach ( $sublinks as $link ) {
994 $s = $this->parseCachedTable( $code, $link, $recursive );
995 $ret = array_merge( $ret, $s );
999 if ( $this->mUcfirst
) {
1000 foreach ( $ret as $k => $v ) {
1001 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1008 * Enclose a string with the "no conversion" tag. This is used by
1009 * various functions in the Parser.
1011 * @param $text String: text to be tagged for no conversion
1012 * @param $noParse Boolean: unused
1013 * @return String: the tagged text
1015 public function markNoConversion( $text, $noParse = false ) {
1016 # don't mark if already marked
1017 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1021 $ret = "-{R|$text}-";
1026 * Convert the sorting key for category links. This should make different
1027 * keys that are variants of each other map to the same key.
1029 * @param $key string
1033 function convertCategoryKey( $key ) {
1038 * Hook to refresh the cache of conversion tables when
1039 * MediaWiki:Conversiontable* is updated.
1042 * @param $article Article object
1043 * @param $user Object: User object for the current user
1044 * @param $text String: article text (?)
1045 * @param $summary String: edit summary of the edit
1046 * @param $isMinor Boolean: was the edit marked as minor?
1047 * @param $isWatch Boolean: did the user watch this page or not?
1049 * @param $flags int Bitfield
1050 * @param $revision Object: new Revision object or null
1051 * @return Boolean: true
1053 function OnArticleSaveComplete( $article, $user, $text, $summary, $isMinor,
1054 $isWatch, $section, $flags, $revision ) {
1055 $titleobj = $article->getTitle();
1056 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1057 $title = $titleobj->getDBkey();
1058 $t = explode( '/', $title, 3 );
1060 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1061 if ( $this->validateVariant( $t[1] ) ) {
1062 $this->reloadTables();
1070 * Armour rendered math against conversion.
1071 * Escape special chars in parsed math text. (in most cases are img elements)
1073 * @param $text String: text to armour against conversion
1074 * @return String: armoured text where { and } have been converted to
1077 public function armourMath( $text ) {
1078 // convert '-{' and '}-' to '-{' and '}-' to prevent
1079 // any unwanted markup appearing in the math image tag.
1080 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
1085 * Get the cached separator pattern for ConverterRule::parseRules()
1087 function getVarSeparatorPattern() {
1088 if ( is_null( $this->mVarSeparatorPattern
) ) {
1089 // varsep_pattern for preg_split:
1090 // text should be splited by ";" only if a valid variant
1091 // name exist after the markup, for example:
1092 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1093 // <span style="font-size:120%;">yyy</span>;}-
1094 // we should split it as:
1096 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1097 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1101 foreach ( $this->mVariants
as $variant ) {
1102 // zh-hans:xxx;zh-hant:yyy
1103 $pat .= $variant . '\s*:|';
1104 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1105 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1108 $this->mVarSeparatorPattern
= $pat;
1110 return $this->mVarSeparatorPattern
;
1115 * Parser for rules of language conversion , parse rules in -{ }- tag.
1117 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1119 class ConverterRule
{
1120 var $mText; // original text in -{text}-
1121 var $mConverter; // LanguageConverter object
1122 var $mRuleDisplay = '';
1123 var $mRuleTitle = false;
1124 var $mRules = '';// string : the text of the rules
1125 var $mRulesAction = 'none';
1126 var $mFlags = array();
1127 var $mVariantFlags = array();
1128 var $mConvTable = array();
1129 var $mBidtable = array();// array of the translation in each variant
1130 var $mUnidtable = array();// array of the translation in each variant
1135 * @param $text String: the text between -{ and }-
1136 * @param $converter LanguageConverter object
1138 public function __construct( $text, $converter ) {
1139 $this->mText
= $text;
1140 $this->mConverter
= $converter;
1144 * Check if variants array in convert array.
1146 * @param $variants Array or string: variant language code
1147 * @return String: translated text
1149 public function getTextInBidtable( $variants ) {
1150 $variants = (array)$variants;
1154 foreach ( $variants as $variant ) {
1155 if ( isset( $this->mBidtable
[$variant] ) ) {
1156 return $this->mBidtable
[$variant];
1163 * Parse flags with syntax -{FLAG| ... }-
1166 function parseFlags() {
1167 $text = $this->mText
;
1169 $variantFlags = array();
1171 $sepPos = strpos( $text, '|' );
1172 if ( $sepPos !== false ) {
1173 $validFlags = $this->mConverter
->mFlags
;
1174 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1175 foreach ( $f as $ff ) {
1177 if ( isset( $validFlags[$ff] ) ) {
1178 $flags[$validFlags[$ff]] = true;
1181 $text = strval( substr( $text, $sepPos +
1 ) );
1186 } elseif ( isset( $flags['R'] ) ) {
1187 $flags = array( 'R' => true );// remove other flags
1188 } elseif ( isset( $flags['N'] ) ) {
1189 $flags = array( 'N' => true );// remove other flags
1190 } elseif ( isset( $flags['-'] ) ) {
1191 $flags = array( '-' => true );// remove other flags
1192 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1194 } elseif ( isset( $flags['H'] ) ) {
1195 // replace A flag, and remove other flags except T
1196 $temp = array( '+' => true, 'H' => true );
1197 if ( isset( $flags['T'] ) ) {
1200 if ( isset( $flags['D'] ) ) {
1205 if ( isset( $flags['A'] ) ) {
1209 if ( isset( $flags['D'] ) ) {
1210 unset( $flags['S'] );
1212 // try to find flags like "zh-hans", "zh-hant"
1213 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1214 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1215 if ( $variantFlags ) {
1216 $variantFlags = array_flip( $variantFlags );
1220 $this->mVariantFlags
= $variantFlags;
1221 $this->mRules
= $text;
1222 $this->mFlags
= $flags;
1226 * Generate conversion table.
1229 function parseRules() {
1230 $rules = $this->mRules
;
1231 $bidtable = array();
1232 $unidtable = array();
1233 $variants = $this->mConverter
->mVariants
;
1234 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1236 $choice = preg_split( $varsep_pattern, $rules );
1238 foreach ( $choice as $c ) {
1239 $v = explode( ':', $c, 2 );
1240 if ( count( $v ) != 2 ) {
1241 // syntax error, skip
1244 $to = trim( $v[1] );
1246 $u = explode( '=>', $v, 2 );
1247 // if $to is empty, strtr() could return a wrong result
1248 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1249 $bidtable[$v] = $to;
1250 } elseif ( count( $u ) == 2 ) {
1251 $from = trim( $u[0] );
1253 if ( array_key_exists( $v, $unidtable )
1254 && !is_array( $unidtable[$v] )
1256 && in_array( $v, $variants ) ) {
1257 $unidtable[$v] = array( $from => $to );
1258 } elseif ( $to && in_array( $v, $variants ) ) {
1259 $unidtable[$v][$from] = $to;
1262 // syntax error, pass
1263 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1264 $bidtable = array();
1265 $unidtable = array();
1269 $this->mBidtable
= $bidtable;
1270 $this->mUnidtable
= $unidtable;
1278 function getRulesDesc() {
1279 $codesep = $this->mConverter
->mDescCodeSep
;
1280 $varsep = $this->mConverter
->mDescVarSep
;
1282 foreach ( $this->mBidtable
as $k => $v ) {
1283 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1285 foreach ( $this->mUnidtable
as $k => $a ) {
1286 foreach ( $a as $from => $to ) {
1287 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1288 "$codesep$to$varsep";
1295 * Parse rules conversion.
1302 function getRuleConvertedStr( $variant ) {
1303 $bidtable = $this->mBidtable
;
1304 $unidtable = $this->mUnidtable
;
1306 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1307 return $this->mRules
;
1309 // display current variant in bidirectional array
1310 $disp = $this->getTextInBidtable( $variant );
1311 // or display current variant in fallbacks
1313 $disp = $this->getTextInBidtable(
1314 $this->mConverter
->getVariantFallbacks( $variant ) );
1316 // or display current variant in unidirectional array
1317 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1318 $disp = array_values( $unidtable[$variant] );
1321 // or display frist text under disable manual convert
1323 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1324 if ( count( $bidtable ) > 0 ) {
1325 $disp = array_values( $bidtable );
1328 $disp = array_values( $unidtable );
1329 $disp = array_values( $disp[0] );
1338 * Generate conversion table for all text.
1341 function generateConvTable() {
1342 // Special case optimisation
1343 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1344 $this->mConvTable
= array();
1348 $bidtable = $this->mBidtable
;
1349 $unidtable = $this->mUnidtable
;
1350 $manLevel = $this->mConverter
->mManualLevel
;
1353 foreach ( $this->mConverter
->mVariants
as $v ) {
1354 /* for bidirectional array
1355 fill in the missing variants, if any,
1357 if ( !isset( $bidtable[$v] ) ) {
1359 $this->mConverter
->getVariantFallbacks( $v );
1360 $vf = $this->getTextInBidtable( $variantFallbacks );
1362 $bidtable[$v] = $vf;
1366 if ( isset( $bidtable[$v] ) ) {
1367 foreach ( $vmarked as $vo ) {
1368 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1369 // or -{H|zh:WordZh;zh-tw:WordTw}-
1370 // or -{-|zh:WordZh;zh-tw:WordTw}-
1371 // to introduce a custom mapping between
1372 // words WordZh and WordTw in the whole text
1373 if ( $manLevel[$v] == 'bidirectional' ) {
1374 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1376 if ( $manLevel[$vo] == 'bidirectional' ) {
1377 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1382 /* for unidirectional array fill to convert tables */
1383 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1384 && isset( $unidtable[$v] ) )
1386 if ( isset( $this->mConvTable
[$v] ) ) {
1387 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1389 $this->mConvTable
[$v] = $unidtable[$v];
1396 * Parse rules and flags.
1397 * @param $variant String: variant language code
1399 public function parse( $variant = null ) {
1401 $variant = $this->mConverter
->getPreferredVariant();
1404 $this->parseFlags();
1405 $flags = $this->mFlags
;
1407 // convert to specified variant
1408 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1409 if ( $this->mVariantFlags
) {
1410 // check if current variant in flags
1411 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1412 // then convert <text to convert> to current language
1413 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1415 } else { // if current variant no in flags,
1416 // then we check its fallback variants.
1418 $this->mConverter
->getVariantFallbacks( $variant );
1419 if( is_array( $variantFallbacks ) ) {
1420 foreach ( $variantFallbacks as $variantFallback ) {
1421 // if current variant's fallback exist in flags
1422 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1423 // then convert <text to convert> to fallback language
1425 $this->mConverter
->autoConvert( $this->mRules
,
1432 $this->mFlags
= $flags = array( 'R' => true );
1435 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1436 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1437 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1438 $this->parseRules();
1440 $rules = $this->mRules
;
1442 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1443 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1444 // fill all variants if text in -{A/H/-|text} without rules
1445 foreach ( $this->mConverter
->mVariants
as $v ) {
1446 $this->mBidtable
[$v] = $rules;
1448 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1449 $this->mFlags
= $flags = array( 'R' => true );
1453 $this->mRuleDisplay
= false;
1454 foreach ( $flags as $flag => $unused ) {
1457 // if we don't do content convert, still strip the -{}- tags
1458 $this->mRuleDisplay
= $rules;
1461 // process N flag: output current variant name
1462 $ruleVar = trim( $rules );
1463 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1464 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1466 $this->mRuleDisplay
= '';
1470 // process D flag: output rules description
1471 $this->mRuleDisplay
= $this->getRulesDesc();
1474 // process H,- flag or T only: output nothing
1475 $this->mRuleDisplay
= '';
1478 $this->mRulesAction
= 'remove';
1479 $this->mRuleDisplay
= '';
1482 $this->mRulesAction
= 'add';
1483 $this->mRuleDisplay
= '';
1486 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1489 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1490 $this->mRuleDisplay
= '';
1493 // ignore unknown flags (but see error case below)
1496 if ( $this->mRuleDisplay
=== false ) {
1497 $this->mRuleDisplay
= '<span class="error">'
1498 . wfMessage( 'converter-manual-rule-error' )->inContentLanguage()->escaped()
1502 $this->generateConvTable();
1506 * @todo FIXME: code this function :)
1508 public function hasRules() {
1513 * Get display text on markup -{...}-
1516 public function getDisplay() {
1517 return $this->mRuleDisplay
;
1521 * Get converted title.
1524 public function getTitle() {
1525 return $this->mRuleTitle
;
1529 * Return how deal with conversion rules.
1532 public function getRulesAction() {
1533 return $this->mRulesAction
;
1537 * Get conversion table. (bidirectional and unidirectional
1541 public function getConvTable() {
1542 return $this->mConvTable
;
1546 * Get conversion rules string.
1549 public function getRules() {
1550 return $this->mRules
;
1554 * Get conversion flags.
1557 public function getFlags() {
1558 return $this->mFlags
;