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
{
32 var $mMainLanguageCode;
33 var $mVariants, $mVariantFallbacks, $mVariantNames;
34 var $mTablesLoaded = false;
36 // 'bidirectional' 'unidirectional' 'disable' for each variant
41 var $mDescCodeSep = ':', $mDescVarSep = ';';
42 var $mUcfirst = false;
43 var $mConvRuleTitle = false;
48 var $mVarSeparatorPattern;
50 const CACHE_VERSION_KEY
= 'VERSION 6';
55 * @param $langobj The Language Object
56 * @param $maincode String: the main language code of this language
57 * @param $variants Array: the supported variants of this language
58 * @param $variantfallbacks Array: the fallback language of each variant
59 * @param $flags Array: defining the custom strings that maps to the flags
60 * @param $manualLevel Array: limit for supported variants
62 public function __construct( $langobj, $maincode,
64 $variantfallbacks = array(),
66 $manualLevel = array() ) {
67 global $wgDisabledVariants, $wgLanguageNames;
68 $this->mLangObj
= $langobj;
69 $this->mMainLanguageCode
= $maincode;
70 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
71 $this->mVariantFallbacks
= $variantfallbacks;
72 $this->mVariantNames
= $wgLanguageNames;
73 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
74 $defaultflags = array(
75 // 'S' show converted text
76 // '+' add rules for alltext
77 // 'E' the gave flags is error
78 // these flags above are reserved for program
79 'A' => 'A', // add rule for convert code (all text convert)
80 'T' => 'T', // title convert
81 'R' => 'R', // raw content
82 'D' => 'D', // convert description (subclass implement)
83 '-' => '-', // remove convert (not implement)
84 'H' => 'H', // add rule for convert code
85 // (but no display in placed code )
86 'N' => 'N' // current variant name
88 $this->mFlags
= array_merge( $defaultflags, $flags );
89 foreach ( $this->mVariants
as $v ) {
90 if ( array_key_exists( $v, $manualLevel ) ) {
91 $this->mManualLevel
[$v] = $manualLevel[$v];
93 $this->mManualLevel
[$v] = 'bidirectional';
95 $this->mFlags
[$v] = $v;
100 * Get all valid variants.
101 * Call this instead of using $this->mVariants directly.
103 * @return Array: contains all valid variants
105 public function getVariants() {
106 return $this->mVariants
;
110 * In case some variant is not defined in the markup, we need
111 * to have some fallback. For example, in zh, normally people
112 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
113 * when zh-sg is preferred but not defined, we will pick zh-hans
114 * in this case. Right now this is only used by zh.
116 * @param $variant String: the language code of the variant
117 * @return String: The code of the fallback language or the
118 * main code if there is no fallback
120 public function getVariantFallbacks( $variant ) {
121 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
122 return $this->mVariantFallbacks
[$variant];
124 return $this->mMainLanguageCode
;
128 * Get the title produced by the conversion rule.
129 * @return String: The converted title text
131 public function getConvRuleTitle() {
132 return $this->mConvRuleTitle
;
136 * Get preferred language variant.
137 * @return String: the preferred language code
139 public function getPreferredVariant() {
140 global $wgDefaultLanguageVariant, $wgUser;
142 $req = $this->getURLVariant();
144 if ( $wgUser->isLoggedIn() && !$req ) {
145 $req = $this->getUserVariant();
149 $req = $this->getHeaderVariant();
152 if ( $wgDefaultLanguageVariant && !$req ) {
153 $req = $this->validateVariant( $wgDefaultLanguageVariant );
156 // This function, unlike the other get*Variant functions, is
157 // not memoized (i.e. there return value is not cached) since
158 // new information might appear during processing after this
163 return $this->mMainLanguageCode
;
167 * Get default variant.
168 * This function would not be affected by user's settings or headers
169 * @return String: the default variant code
171 public function getDefaultVariant() {
172 global $wgDefaultLanguageVariant;
174 $req = $this->getURLVariant();
176 if ( $wgDefaultLanguageVariant && !$req ) {
177 $req = $this->validateVariant( $wgDefaultLanguageVariant );
183 return $this->mMainLanguageCode
;
187 * Validate the variant
188 * @param $variant String: the variant to validate
189 * @return Mixed: returns the variant if it is valid, null otherwise
191 protected function validateVariant( $variant = null ) {
192 if ( $variant !== null &&
193 in_array( $variant, $this->mVariants
) ) {
200 * Get the variant specified in the URL
202 * @return Mixed: variant if one found, false otherwise.
204 public function getURLVariant() {
207 if ( $this->mURLVariant
) {
208 return $this->mURLVariant
;
211 // see if the preference is set in the request
212 $ret = $wgRequest->getText( 'variant' );
215 $ret = $wgRequest->getVal( 'uselang' );
218 return $this->mURLVariant
= $this->validateVariant( $ret );
222 * Determine if the user has a variant set.
224 * @return Mixed: variant if one found, false otherwise.
226 protected function getUserVariant() {
229 // memoizing this function wreaks havoc on parserTest.php
230 /* if ( $this->mUserVariant ) { */
231 /* return $this->mUserVariant; */
234 // get language variant preference from logged in users
235 // Don't call this on stub objects because that causes infinite
236 // recursion during initialisation
237 if ( $wgUser->isLoggedIn() ) {
238 $ret = $wgUser->getOption( 'variant' );
241 // figure out user lang without constructing wgLang to avoid
242 // infinite recursion
243 $ret = $wgUser->getOption( 'language' );
246 return $this->mUserVariant
= $this->validateVariant( $ret );
250 * Determine the language variant from the Accept-Language header.
252 * @return Mixed: variant if one found, false otherwise.
254 protected function getHeaderVariant() {
257 if ( $this->mHeaderVariant
) {
258 return $this->mHeaderVariant
;
261 // see if some supported language variant is set in the
263 $languages = array_keys( $wgRequest->getAcceptLang() );
264 if ( empty( $languages ) ) {
268 $fallback_languages = array();
269 foreach ( $languages as $language ) {
270 $this->mHeaderVariant
= $this->validateVariant( $language );
271 if ( $this->mHeaderVariant
) {
275 // To see if there are fallbacks of current language.
276 // We record these fallback variants, and process
278 $fallbacks = $this->getVariantFallbacks( $language );
279 if ( is_string( $fallbacks ) ) {
280 $fallback_languages[] = $fallbacks;
281 } elseif ( is_array( $fallbacks ) ) {
282 $fallback_languages =
283 array_merge( $fallback_languages,
288 if ( !$this->mHeaderVariant
) {
289 // process fallback languages now
290 $fallback_languages = array_unique( $fallback_languages );
291 foreach ( $fallback_languages as $language ) {
292 $this->mHeaderVariant
= $this->validateVariant( $language );
293 if ( $this->mHeaderVariant
) {
299 return $this->mHeaderVariant
;
303 * Caption convert, base on preg_replace_callback.
305 * To convert text in "title" or "alt", like '<img alt="text" ... '
306 * or '<span title="text" ... '
308 * @return String like ' alt="yyyy"' or ' title="yyyy"'
310 protected function captionConvert( $matches ) {
311 // TODO: cache the preferred variant in every autoConvert() process,
312 // this helps improve performance in a way.
313 $toVariant = $this->getPreferredVariant();
314 $title = $matches[1];
317 // we convert captions except URL
318 if ( !strpos( $text, '://' ) ) {
319 $text = $this->translate( $text, $toVariant );
322 // remove HTML tags to prevent disrupting the layout
323 $text = preg_replace( '/<[^>]+>/', '', $text );
324 // escape HTML special chars to prevent disrupting the layout
325 $text = htmlspecialchars( $text );
327 return " {$title}=\"{$text}\"";
331 * Dictionary-based conversion.
332 * This function would not parse the conversion rules.
333 * If you want to parse rules, try to use convert() or
336 * @param $text String: the text to be converted
337 * @param $toVariant String: the target language code
338 * @return String: the converted text
340 public function autoConvert( $text, $toVariant = false ) {
341 wfProfileIn( __METHOD__
);
346 $toVariant = $this->getPreferredVariant();
348 wfProfileOut( __METHOD__
);
353 /* we convert everything except:
354 1. html markups (anything between < and >)
356 3. place holders created by the parser
359 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
360 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
365 // this one is needed when the text is inside an html markup
366 $htmlfix = '|<[^>]+$|^[^<>]*>';
368 // disable convert to variants between <code></code> tags
369 $codefix = '<code>.+?<\/code>|';
370 // disable convertsion of <script type="text/javascript"> ... </script>
371 $scriptfix = '<script.*?>.*?<\/script>|';
372 // disable conversion of <pre xxxx> ... </pre>
373 $prefix = '<pre.*?>.*?<\/pre>|';
375 $reg = '/' . $codefix . $scriptfix . $prefix .
376 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
378 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
380 $m = array_shift( $matches );
382 $ret = $this->translate( $m[0], $toVariant );
383 $mstart = $m[1] +
strlen( $m[0] );
385 // enable convertsion of '<img alt="xxxx" ... '
386 // or '<span title="xxxx" ... '
387 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
392 foreach ( $matches as $m ) {
393 $mark = substr( $text, $mstart, $m[1] - $mstart );
394 $mark = preg_replace_callback( $captionpattern,
395 array( &$this, 'captionConvert' ),
397 // Let's convert the trtext only once,
398 // it would give us more performance improvement
400 $trtext .= $m[0] . $trtextmark;
401 $mstart = $m[1] +
strlen( $m[0] );
404 $trtext = $this->translate( $trtext, $toVariant );
405 $trtext = StringUtils
::explode( $trtextmark, $trtext );
406 foreach ( $trtext as $t ) {
407 $ret .= array_shift( $notrtext );
410 wfProfileOut( __METHOD__
);
415 * Translate a string to a variant.
416 * Doesn't parse rules or do any of that other stuff, for that use
417 * convert() or convertTo().
419 * @param $text String: text to convert
420 * @param $variant String: variant language code
421 * @return String: translated text
423 protected function translate( $text, $variant ) {
424 wfProfileIn( __METHOD__
);
425 // If $text is empty or only includes spaces, do nothing
426 // Otherwise translate it
427 if ( trim( $text ) ) {
429 $text = $this->mTables
[$variant]->replace( $text );
431 wfProfileOut( __METHOD__
);
436 * Call translate() to convert text to all valid variants.
438 * @param $text String: the text to be converted
439 * @return Array: variant => converted text
441 public function autoConvertToAllVariants( $text ) {
442 wfProfileIn( __METHOD__
);
446 foreach ( $this->mVariants
as $variant ) {
447 $ret[$variant] = $this->translate( $text, $variant );
450 wfProfileOut( __METHOD__
);
455 * Convert link text to all valid variants.
456 * In the first, this function only convert text outside the
457 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
458 * titles, the text will get all converted always.
459 * So I removed this feature and deprecated the function.
461 * @param $text String: the text to be converted
462 * @return Array: variant => converted text
463 * @deprecated Use autoConvertToAllVariants() instead
465 public function convertLinkToAllVariants( $text ) {
466 return $this->autoConvertToAllVariants( $text );
470 * Apply manual conversion rules.
472 * @param $convRule Object: Object of ConverterRule
474 protected function applyManualConv( $convRule ) {
475 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
477 // Bug 24072: $mConvRuleTitle was overwritten by other manual
478 // rule(s) not for title, this breaks the title conversion.
479 $newConvRuleTitle = $convRule->getTitle();
480 if ( $newConvRuleTitle ) {
481 // So I add an empty check for getTitle()
482 $this->mConvRuleTitle
= $newConvRuleTitle;
485 // merge/remove manual conversion rules to/from global table
486 $convTable = $convRule->getConvTable();
487 $action = $convRule->getRulesAction();
488 foreach ( $convTable as $variant => $pair ) {
489 if ( !$this->validateVariant( $variant ) ) {
493 if ( $action == 'add' ) {
494 foreach ( $pair as $from => $to ) {
495 // to ensure that $from and $to not be left blank
496 // so $this->translate() could always return a string
497 if ( $from ||
$to ) {
498 // more efficient than array_merge(), about 2.5 times.
499 $this->mTables
[$variant]->setPair( $from, $to );
502 } elseif ( $action == 'remove' ) {
503 $this->mTables
[$variant]->removeArray( $pair );
509 * Auto convert a Title object to a readable string in the
512 *@param $title Object: a object of Title
513 *@return String: converted title text
515 public function convertTitle( $title ) {
516 $variant = $this->getPreferredVariant();
517 $index = $title->getNamespace();
518 if ( $index === NS_MAIN
) {
521 // first let's check if a message has given us a converted name
522 $nsConvKey = 'conversion-ns' . $index;
523 if ( !wfEmptyMsg( $nsConvKey ) ) {
524 $text = wfMsgForContentNoTrans( $nsConvKey );
526 // the message does not exist, try retrieve it from the current
527 // variant's namespace names.
528 $langObj = $this->mLangObj
->factory( $variant );
529 $text = $langObj->getFormattedNsText( $index );
533 $text .= $title->getText();
534 $text = $this->translate( $text, $variant );
539 * Convert text to different variants of a language. The automatic
540 * conversion is done in autoConvert(). Here we parse the text
541 * marked with -{}-, which specifies special conversions of the
542 * text that can not be accomplished in autoConvert().
544 * Syntax of the markup:
545 * -{code1:text1;code2:text2;...}- or
546 * -{flags|code1:text1;code2:text2;...}- or
547 * -{text}- in which case no conversion should take place for text
549 * @param $text String: text to be converted
550 * @return String: converted text
552 public function convert( $text ) {
553 $variant = $this->getPreferredVariant();
554 return $this->convertTo( $text, $variant );
558 * Same as convert() except a extra parameter to custom variant.
560 * @param $text String: text to be converted
561 * @param $variant String: the target variant code
562 * @return String: converted text
564 public function convertTo( $text, $variant ) {
565 global $wgDisableLangConversion;
566 if ( $wgDisableLangConversion ) return $text;
567 return $this->recursiveConvertTopLevel( $text, $variant );
571 * Recursively convert text on the outside. Allow to use nested
572 * markups to custom rules.
574 * @param $text String: text to be converted
575 * @param $variant String: the target variant code
576 * @param $depth Integer: depth of recursion
577 * @return String: converted text
579 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
582 $length = strlen( $text );
583 while ( $startPos < $length ) {
584 $pos = strpos( $text, '-{', $startPos );
586 if ( $pos === false ) {
587 // No more markup, append final segment
588 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
593 // Append initial segment
594 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
599 // Do recursive conversion
600 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
607 * Recursively convert text on the inside.
609 * @param $text String: text to be converted
610 * @param $variant String: the target variant code
611 * @param $depth Integer: depth of recursion
612 * @return String: converted text
614 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
615 // Quick sanity check (no function calls)
616 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
617 throw new MWException( __METHOD__
. ': invalid input string' );
622 $warningDone = false;
623 $length = strlen( $text );
625 while ( $startPos < $length ) {
627 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
637 // Append initial segment
638 $inner .= substr( $text, $startPos, $pos - $startPos );
646 if ( $depth >= $this->mMaxDepth
) {
648 if ( !$warningDone ) {
649 $inner .= '<span class="error">' .
650 wfMsgForContent( 'language-converter-depth-warning',
658 // Recursively parse another rule
659 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
664 $rule = new ConverterRule( $inner, $this );
665 $rule->parse( $variant );
666 $this->applyManualConv( $rule );
667 return $rule->getDisplay();
669 throw new MWException( __METHOD__
. ': invalid regex match' );
674 if ( $startPos < $length ) {
675 $inner .= substr( $text, $startPos );
678 return '-{' . $this->autoConvert( $inner, $variant );
682 * If a language supports multiple variants, it is
683 * possible that non-existing link in one variant
684 * actually exists in another variant. This function
685 * tries to find it. See e.g. LanguageZh.php
687 * @param $link String: the name of the link
688 * @param $nt Mixed: the title object of the link
689 * @param $ignoreOtherCond Boolean: to disable other conditions when
690 * we need to transclude a template or update a category's link
691 * @return Null, the input parameters may be modified upon return
693 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
694 # If the article has already existed, there is no need to
695 # check it again, otherwise it may cause a fault.
696 if ( is_object( $nt ) && $nt->exists() ) {
700 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
702 $isredir = $wgRequest->getText( 'redirect', 'yes' );
703 $action = $wgRequest->getText( 'action' );
704 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
705 $disableLinkConversion = $wgDisableLangConversion
706 ||
$wgDisableTitleConversion;
707 $linkBatch = new LinkBatch();
711 if ( $disableLinkConversion ||
712 ( !$ignoreOtherCond &&
715 ||
$action == 'submit'
716 ||
$linkconvert == 'no'
717 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
721 if ( is_object( $nt ) ) {
722 $ns = $nt->getNamespace();
725 $variants = $this->autoConvertToAllVariants( $link );
726 if ( !$variants ) { // give up
732 foreach ( $variants as $v ) {
734 $varnt = Title
::newFromText( $v, $ns );
735 if ( !is_null( $varnt ) ) {
736 $linkBatch->addObj( $varnt );
742 // fetch all variants in single query
743 $linkBatch->execute();
745 foreach ( $titles as $varnt ) {
746 if ( $varnt->getArticleID() > 0 ) {
748 $link = $varnt->getText();
755 * Returns language specific hash options.
757 public function getExtraHashOptions() {
758 $variant = $this->getPreferredVariant();
759 return '!' . $variant ;
763 * Load default conversion tables.
764 * This method must be implemented in derived class.
768 function loadDefaultTables() {
769 $name = get_class( $this );
770 wfDie( "Must implement loadDefaultTables() method in class $name" );
774 * Load conversion tables either from the cache or the disk.
777 function loadTables( $fromcache = true ) {
778 if ( $this->mTablesLoaded
) {
782 wfProfileIn( __METHOD__
);
783 $this->mTablesLoaded
= true;
784 $this->mTables
= false;
786 wfProfileIn( __METHOD__
. '-cache' );
787 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
788 wfProfileOut( __METHOD__
. '-cache' );
791 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
792 wfProfileIn( __METHOD__
. '-recache' );
793 // not in cache, or we need a fresh reload.
794 // we will first load the default tables
795 // then update them using things in MediaWiki:Zhconversiontable/*
796 $this->loadDefaultTables();
797 foreach ( $this->mVariants
as $var ) {
798 $cached = $this->parseCachedTable( $var );
799 $this->mTables
[$var]->mergeArray( $cached );
802 $this->postLoadTables();
803 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
805 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
806 wfProfileOut( __METHOD__
. '-recache' );
808 wfProfileOut( __METHOD__
);
812 * Hook for post processig after conversion tables are loaded.
815 function postLoadTables() { }
818 * Reload the conversion tables.
822 function reloadTables() {
823 if ( $this->mTables
) {
824 unset( $this->mTables
);
826 $this->mTablesLoaded
= false;
827 $this->loadTables( false );
832 * Parse the conversion table stored in the cache.
834 * The tables should be in blocks of the following form:
841 * To make the tables more manageable, subpages are allowed
842 * and will be parsed recursively if $recursive == true.
845 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
846 static $parsed = array();
848 $key = 'Conversiontable/' . $code;
850 $key .= '/' . $subpage;
852 if ( array_key_exists( $key, $parsed ) ) {
856 if ( strpos( $code, '/' ) === false ) {
857 $txt = MessageCache
::singleton()->get( 'Conversiontable', true, $code );
858 if ( $txt === false ) {
859 # FIXME: this method doesn't seem to be expecting
860 # this possible outcome...
861 $txt = '<Conversiontable>';
864 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
865 "Conversiontable/$code" );
866 if ( $title && $title->exists() ) {
867 $article = new Article( $title );
868 $txt = $article->getContents();
874 // get all subpage links of the form
875 // [[MediaWiki:conversiontable/zh-xx/...|...]]
876 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
878 $subs = StringUtils
::explode( '[[', $txt );
880 foreach ( $subs as $sub ) {
881 $link = explode( ']]', $sub, 2 );
882 if ( count( $link ) != 2 ) {
885 $b = explode( '|', $link[0], 2 );
886 $b = explode( '/', trim( $b[0] ), 3 );
887 if ( count( $b ) == 3 ) {
893 if ( $b[0] == $linkhead && $b[1] == $code ) {
894 $sublinks[] = $sublink;
898 // parse the mappings in this page
899 $blocks = StringUtils
::explode( '-{', $txt );
902 foreach ( $blocks as $block ) {
904 // Skip the part before the first -{
908 $mappings = explode( '}-', $block, 2 );
909 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
911 $table = StringUtils
::explode( ';', $stripped );
912 foreach ( $table as $t ) {
913 $m = explode( '=>', $t, 3 );
914 if ( count( $m ) != 2 )
916 // trim any trailling comments starting with '//'
917 $tt = explode( '//', $m[1], 2 );
918 $ret[trim( $m[0] )] = trim( $tt[0] );
921 $parsed[$key] = true;
923 // recursively parse the subpages
925 foreach ( $sublinks as $link ) {
926 $s = $this->parseCachedTable( $code, $link, $recursive );
927 $ret = array_merge( $ret, $s );
931 if ( $this->mUcfirst
) {
932 foreach ( $ret as $k => $v ) {
933 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
940 * Enclose a string with the "no conversion" tag. This is used by
941 * various functions in the Parser.
943 * @param $text String: text to be tagged for no conversion
944 * @param $noParse Unused (?)
945 * @return String: the tagged text
947 public function markNoConversion( $text, $noParse = false ) {
948 # don't mark if already marked
949 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
953 $ret = "-{R|$text}-";
958 * Convert the sorting key for category links. This should make different
959 * keys that are variants of each other map to the same key.
961 function convertCategoryKey( $key ) {
966 * Hook to refresh the cache of conversion tables when
967 * MediaWiki:conversiontable* is updated.
970 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
971 $iswatch, $section, $flags, $revision ) {
972 $titleobj = $article->getTitle();
973 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
974 $title = $titleobj->getDBkey();
975 $t = explode( '/', $title, 3 );
977 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
978 if ( $this->validateVariant( $t[1] ) ) {
979 $this->reloadTables();
987 * Armour rendered math against conversion.
988 * Escape special chars in parsed math text.(in most cases are img elements)
990 public function armourMath( $text ) {
991 // convert '-{' and '}-' to '-{' and '}-' to prevent
992 // any unwanted markup appearing in the math image tag.
993 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
998 * Get the cached separator pattern for ConverterRule::parseRules()
1000 function getVarSeparatorPattern() {
1001 if ( is_null( $this->mVarSeparatorPattern
) ) {
1002 // varsep_pattern for preg_split:
1003 // text should be splited by ";" only if a valid variant
1004 // name exist after the markup, for example:
1005 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1006 // <span style="font-size:120%;">yyy</span>;}-
1007 // we should split it as:
1009 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1010 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1014 foreach ( $this->mVariants
as $variant ) {
1015 // zh-hans:xxx;zh-hant:yyy
1016 $pat .= $variant . '\s*:|';
1017 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1018 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1021 $this->mVarSeparatorPattern
= $pat;
1023 return $this->mVarSeparatorPattern
;
1028 * Parser for rules of language conversion , parse rules in -{ }- tag.
1030 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1032 class ConverterRule
{
1033 var $mText; // original text in -{text}-
1034 var $mConverter; // LanguageConverter object
1035 var $mManualCodeError = '<strong class="error">code error!</strong>';
1036 var $mRuleDisplay = '';
1037 var $mRuleTitle = false;
1038 var $mRules = '';// string : the text of the rules
1039 var $mRulesAction = 'none';
1040 var $mFlags = array();
1041 var $mVariantFlags = array();
1042 var $mConvTable = array();
1043 var $mBidtable = array();// array of the translation in each variant
1044 var $mUnidtable = array();// array of the translation in each variant
1049 * @param $text String: the text between -{ and }-
1050 * @param $converter LanguageConverter object
1052 public function __construct( $text, $converter ) {
1053 $this->mText
= $text;
1054 $this->mConverter
= $converter;
1058 * Check if variants array in convert array.
1060 * @param $variants Array or string: variant language code
1061 * @return String: translated text
1063 public function getTextInBidtable( $variants ) {
1064 $variants = (array)$variants;
1068 foreach ( $variants as $variant ) {
1069 if ( isset( $this->mBidtable
[$variant] ) ) {
1070 return $this->mBidtable
[$variant];
1077 * Parse flags with syntax -{FLAG| ... }-
1080 function parseFlags() {
1081 $text = $this->mText
;
1083 $variantFlags = array();
1085 $sepPos = strpos( $text, '|' );
1086 if ( $sepPos !== false ) {
1087 $validFlags = $this->mConverter
->mFlags
;
1088 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1089 foreach ( $f as $ff ) {
1091 if ( isset( $validFlags[$ff] ) ) {
1092 $flags[$validFlags[$ff]] = true;
1095 $text = strval( substr( $text, $sepPos +
1 ) );
1100 } elseif ( isset( $flags['R'] ) ) {
1101 $flags = array( 'R' => true );// remove other flags
1102 } elseif ( isset( $flags['N'] ) ) {
1103 $flags = array( 'N' => true );// remove other flags
1104 } elseif ( isset( $flags['-'] ) ) {
1105 $flags = array( '-' => true );// remove other flags
1106 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1108 } elseif ( isset( $flags['H'] ) ) {
1109 // replace A flag, and remove other flags except T
1110 $temp = array( '+' => true, 'H' => true );
1111 if ( isset( $flags['T'] ) ) {
1114 if ( isset( $flags['D'] ) ) {
1119 if ( isset( $flags['A'] ) ) {
1123 if ( isset( $flags['D'] ) ) {
1124 unset( $flags['S'] );
1126 // try to find flags like "zh-hans", "zh-hant"
1127 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1128 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1129 if ( $variantFlags ) {
1130 $variantFlags = array_flip( $variantFlags );
1134 $this->mVariantFlags
= $variantFlags;
1135 $this->mRules
= $text;
1136 $this->mFlags
= $flags;
1140 * Generate conversion table.
1143 function parseRules() {
1144 $rules = $this->mRules
;
1145 $bidtable = array();
1146 $unidtable = array();
1147 $variants = $this->mConverter
->mVariants
;
1148 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1150 $choice = preg_split( $varsep_pattern, $rules );
1152 foreach ( $choice as $c ) {
1153 $v = explode( ':', $c, 2 );
1154 if ( count( $v ) != 2 ) {
1155 // syntax error, skip
1158 $to = trim( $v[1] );
1160 $u = explode( '=>', $v, 2 );
1161 // if $to is empty, strtr() could return a wrong result
1162 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1163 $bidtable[$v] = $to;
1164 } elseif ( count( $u ) == 2 ) {
1165 $from = trim( $u[0] );
1167 if ( array_key_exists( $v, $unidtable )
1168 && !is_array( $unidtable[$v] )
1170 && in_array( $v, $variants ) ) {
1171 $unidtable[$v] = array( $from => $to );
1172 } elseif ( $to && in_array( $v, $variants ) ) {
1173 $unidtable[$v][$from] = $to;
1176 // syntax error, pass
1177 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1178 $bidtable = array();
1179 $unidtable = array();
1183 $this->mBidtable
= $bidtable;
1184 $this->mUnidtable
= $unidtable;
1190 function getRulesDesc() {
1191 $codesep = $this->mConverter
->mDescCodeSep
;
1192 $varsep = $this->mConverter
->mDescVarSep
;
1194 foreach ( $this->mBidtable
as $k => $v ) {
1195 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1197 foreach ( $this->mUnidtable
as $k => $a ) {
1198 foreach ( $a as $from => $to ) {
1199 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1200 "$codesep$to$varsep";
1207 * Parse rules conversion.
1210 function getRuleConvertedStr( $variant ) {
1211 $bidtable = $this->mBidtable
;
1212 $unidtable = $this->mUnidtable
;
1214 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1215 return $this->mRules
;
1217 // display current variant in bidirectional array
1218 $disp = $this->getTextInBidtable( $variant );
1219 // or display current variant in fallbacks
1221 $disp = $this->getTextInBidtable(
1222 $this->mConverter
->getVariantFallbacks( $variant ) );
1224 // or display current variant in unidirectional array
1225 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1226 $disp = array_values( $unidtable[$variant] );
1229 // or display frist text under disable manual convert
1231 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1232 if ( count( $bidtable ) > 0 ) {
1233 $disp = array_values( $bidtable );
1236 $disp = array_values( $unidtable );
1237 $disp = array_values( $disp[0] );
1246 * Generate conversion table for all text.
1249 function generateConvTable() {
1250 // Special case optimisation
1251 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1252 $this->mConvTable
= array();
1256 $bidtable = $this->mBidtable
;
1257 $unidtable = $this->mUnidtable
;
1258 $manLevel = $this->mConverter
->mManualLevel
;
1261 foreach ( $this->mConverter
->mVariants
as $v ) {
1262 /* for bidirectional array
1263 fill in the missing variants, if any,
1265 if ( !isset( $bidtable[$v] ) ) {
1267 $this->mConverter
->getVariantFallbacks( $v );
1268 $vf = $this->getTextInBidtable( $variantFallbacks );
1270 $bidtable[$v] = $vf;
1274 if ( isset( $bidtable[$v] ) ) {
1275 foreach ( $vmarked as $vo ) {
1276 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1277 // or -{H|zh:WordZh;zh-tw:WordTw}-
1278 // or -{-|zh:WordZh;zh-tw:WordTw}-
1279 // to introduce a custom mapping between
1280 // words WordZh and WordTw in the whole text
1281 if ( $manLevel[$v] == 'bidirectional' ) {
1282 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1284 if ( $manLevel[$vo] == 'bidirectional' ) {
1285 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1290 /*for unidirectional array fill to convert tables */
1291 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1292 && isset( $unidtable[$v] ) )
1294 if ( isset( $this->mConvTable
[$v] ) ) {
1295 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1297 $this->mConvTable
[$v] = $unidtable[$v];
1304 * Parse rules and flags.
1307 function parse( $variant = NULL ) {
1309 $variant = $this->mConverter
->getPreferredVariant();
1312 $this->parseFlags();
1313 $flags = $this->mFlags
;
1315 // convert to specified variant
1316 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1317 if ( $this->mVariantFlags
) {
1318 // check if current variant in flags
1319 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1320 // then convert <text to convert> to current language
1321 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1323 } else { // if current variant no in flags,
1324 // then we check its fallback variants.
1326 $this->mConverter
->getVariantFallbacks( $variant );
1327 foreach ( $variantFallbacks as $variantFallback ) {
1328 // if current variant's fallback exist in flags
1329 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1330 // then convert <text to convert> to fallback language
1332 $this->mConverter
->autoConvert( $this->mRules
,
1338 $this->mFlags
= $flags = array( 'R' => true );
1341 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1342 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1343 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1344 $this->parseRules();
1346 $rules = $this->mRules
;
1348 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1349 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1350 // fill all variants if text in -{A/H/-|text} without rules
1351 foreach ( $this->mConverter
->mVariants
as $v ) {
1352 $this->mBidtable
[$v] = $rules;
1354 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1355 $this->mFlags
= $flags = array( 'R' => true );
1359 $this->mRuleDisplay
= false;
1360 foreach ( $flags as $flag => $unused ) {
1363 // if we don't do content convert, still strip the -{}- tags
1364 $this->mRuleDisplay
= $rules;
1367 // process N flag: output current variant name
1368 $ruleVar = trim( $rules );
1369 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1370 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1372 $this->mRuleDisplay
= '';
1376 // process D flag: output rules description
1377 $this->mRuleDisplay
= $this->getRulesDesc();
1380 // process H,- flag or T only: output nothing
1381 $this->mRuleDisplay
= '';
1384 $this->mRulesAction
= 'remove';
1385 $this->mRuleDisplay
= '';
1388 $this->mRulesAction
= 'add';
1389 $this->mRuleDisplay
= '';
1392 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1395 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1396 $this->mRuleDisplay
= '';
1399 // ignore unknown flags (but see error case below)
1402 if ( $this->mRuleDisplay
=== false ) {
1403 $this->mRuleDisplay
= $this->mManualCodeError
;
1406 $this->generateConvTable();
1412 function hasRules() {
1417 * Get display text on markup -{...}-
1420 function getDisplay() {
1421 return $this->mRuleDisplay
;
1425 * Get converted title.
1428 function getTitle() {
1429 return $this->mRuleTitle
;
1433 * Return how deal with conversion rules.
1436 function getRulesAction() {
1437 return $this->mRulesAction
;
1441 * Get conversion table. ( bidirectional and unidirectional
1442 * conversion table )
1445 function getConvTable() {
1446 return $this->mConvTable
;
1450 * Get conversion rules string.
1453 function getRules() {
1454 return $this->mRules
;
1458 * Get conversion flags.
1461 function getFlags() {
1462 return $this->mFlags
;