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 $toVariant = $this->getPreferredVariant();
312 $title = $matches[1];
314 // we convert captions except URL
315 if ( !strpos( $text, '://' ) ) {
316 $text = $this->translate( $text, $toVariant );
318 return " $title=\"$text\"";
322 * Dictionary-based conversion.
323 * This function would not parse the conversion rules.
324 * If you want to parse rules, try to use convert() or
327 * @param $text String: the text to be converted
328 * @param $toVariant String: the target language code
329 * @return String: the converted text
331 public function autoConvert( $text, $toVariant = false ) {
332 wfProfileIn( __METHOD__
);
337 $toVariant = $this->getPreferredVariant();
343 /* we convert everything except:
344 1. html markups (anything between < and >)
346 3. place holders created by the parser
349 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
350 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
355 // this one is needed when the text is inside an html markup
356 $htmlfix = '|<[^>]+$|^[^<>]*>';
358 // disable convert to variants between <code></code> tags
359 $codefix = '<code>.+?<\/code>|';
360 // disable convertsion of <script type="text/javascript"> ... </script>
361 $scriptfix = '<script.*?>.*?<\/script>|';
362 // disable conversion of <pre xxxx> ... </pre>
363 $prefix = '<pre.*?>.*?<\/pre>|';
365 $reg = '/' . $codefix . $scriptfix . $prefix .
366 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
368 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
370 $m = array_shift( $matches );
372 $ret = $this->translate( $m[0], $toVariant );
373 $mstart = $m[1] +
strlen( $m[0] );
375 // enable convertsion of '<img alt="xxxx" ... '
376 // or '<span title="xxxx" ... '
377 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
382 foreach ( $matches as $m ) {
383 $mark = substr( $text, $mstart, $m[1] - $mstart );
384 $mark = preg_replace_callback( $captionpattern,
385 array( &$this, 'captionConvert' ),
387 // Let's convert the trtext only once,
388 // it would give us more performance improvement
390 $trtext .= $m[0] . $trtextmark;
391 $mstart = $m[1] +
strlen( $m[0] );
394 $trtext = $this->translate( $trtext, $toVariant );
395 $trtext = StringUtils
::explode( $trtextmark, $trtext );
396 foreach ( $trtext as $t ) {
397 $ret .= array_shift( $notrtext );
400 wfProfileOut( __METHOD__
);
405 * Translate a string to a variant.
406 * Doesn't parse rules or do any of that other stuff, for that use
407 * convert() or convertTo().
409 * @param $text String: text to convert
410 * @param $variant String: variant language code
411 * @return String: translated text
413 protected function translate( $text, $variant ) {
414 wfProfileIn( __METHOD__
);
415 // If $text is empty or only includes spaces, do nothing
416 // Otherwise translate it
417 if ( trim( $text ) ) {
419 $text = $this->mTables
[$variant]->replace( $text );
421 wfProfileOut( __METHOD__
);
426 * Call translate() to convert text to all valid variants.
428 * @param $text String: the text to be converted
429 * @return Array: variant => converted text
431 public function autoConvertToAllVariants( $text ) {
432 wfProfileIn( __METHOD__
);
436 foreach ( $this->mVariants
as $variant ) {
437 $ret[$variant] = $this->translate( $text, $variant );
440 wfProfileOut( __METHOD__
);
445 * Convert link text to all valid variants.
446 * In the first, this function only convert text outside the
447 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
448 * titles, the text will get all converted always.
449 * So I removed this feature and deprecated the function.
451 * @param $text String: the text to be converted
452 * @return Array: variant => converted text
453 * @deprecated Use autoConvertToAllVariants() instead
455 public function convertLinkToAllVariants( $text ) {
456 return $this->autoConvertToAllVariants( $text );
460 * Apply manual conversion rules.
462 * @param $convRule Object: Object of ConverterRule
464 protected function applyManualConv( $convRule ) {
465 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
467 // Bug 24072: $mConvRuleTitle was overwritten by other manual
468 // rule(s) not for title, this breaks the title conversion.
469 $newConvRuleTitle = $convRule->getTitle();
470 if ( $newConvRuleTitle ) {
471 // So I add an empty check for getTitle()
472 $this->mConvRuleTitle
= $newConvRuleTitle;
475 // merge/remove manual conversion rules to/from global table
476 $convTable = $convRule->getConvTable();
477 $action = $convRule->getRulesAction();
478 foreach ( $convTable as $variant => $pair ) {
479 if ( !$this->validateVariant( $variant ) ) {
483 if ( $action == 'add' ) {
484 foreach ( $pair as $from => $to ) {
485 // to ensure that $from and $to not be left blank
486 // so $this->translate() could always return a string
487 if ( $from ||
$to ) {
488 // more efficient than array_merge(), about 2.5 times.
489 $this->mTables
[$variant]->setPair( $from, $to );
492 } elseif ( $action == 'remove' ) {
493 $this->mTables
[$variant]->removeArray( $pair );
499 * Auto convert a Title object to a readable string in the
502 *@param $title Object: a object of Title
503 *@return String: converted title text
505 public function convertTitle( $title ) {
506 $variant = $this->getPreferredVariant();
507 $index = $title->getNamespace();
508 if ( $index === NS_MAIN
) {
511 // first let's check if a message has given us a converted name
512 $nsConvKey = 'conversion-ns' . $index;
513 if ( !wfEmptyMsg( $nsConvKey ) ) {
514 $text = wfMsgForContentNoTrans( $nsConvKey );
516 // the message does not exist, try retrieve it from the current
517 // variant's namespace names.
518 $langObj = $this->mLangObj
->factory( $variant );
519 $text = $langObj->getFormattedNsText( $index );
523 $text .= $title->getText();
524 $text = $this->translate( $text, $variant );
529 * Convert text to different variants of a language. The automatic
530 * conversion is done in autoConvert(). Here we parse the text
531 * marked with -{}-, which specifies special conversions of the
532 * text that can not be accomplished in autoConvert().
534 * Syntax of the markup:
535 * -{code1:text1;code2:text2;...}- or
536 * -{flags|code1:text1;code2:text2;...}- or
537 * -{text}- in which case no conversion should take place for text
539 * @param $text String: text to be converted
540 * @return String: converted text
542 public function convert( $text ) {
543 $variant = $this->getPreferredVariant();
544 return $this->convertTo( $text, $variant );
548 * Same as convert() except a extra parameter to custom variant.
550 * @param $text String: text to be converted
551 * @param $variant String: the target variant code
552 * @return String: converted text
554 public function convertTo( $text, $variant ) {
555 global $wgDisableLangConversion;
556 if ( $wgDisableLangConversion ) return $text;
557 return $this->recursiveConvertTopLevel( $text, $variant );
561 * Recursively convert text on the outside. Allow to use nested
562 * markups to custom rules.
564 * @param $text String: text to be converted
565 * @param $variant String: the target variant code
566 * @param $depth Integer: depth of recursion
567 * @return String: converted text
569 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
572 $length = strlen( $text );
573 while ( $startPos < $length ) {
574 $pos = strpos( $text, '-{', $startPos );
576 if ( $pos === false ) {
577 // No more markup, append final segment
578 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
583 // Append initial segment
584 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
589 // Do recursive conversion
590 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
597 * Recursively convert text on the inside.
599 * @param $text String: text to be converted
600 * @param $variant String: the target variant code
601 * @param $depth Integer: depth of recursion
602 * @return String: converted text
604 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
605 // Quick sanity check (no function calls)
606 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
607 throw new MWException( __METHOD__
. ': invalid input string' );
612 $warningDone = false;
613 $length = strlen( $text );
615 while ( $startPos < $length ) {
617 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
627 // Append initial segment
628 $inner .= substr( $text, $startPos, $pos - $startPos );
636 if ( $depth >= $this->mMaxDepth
) {
638 if ( !$warningDone ) {
639 $inner .= '<span class="error">' .
640 wfMsgForContent( 'language-converter-depth-warning',
648 // Recursively parse another rule
649 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
654 $rule = new ConverterRule( $inner, $this );
655 $rule->parse( $variant );
656 $this->applyManualConv( $rule );
657 return $rule->getDisplay();
659 throw new MWException( __METHOD__
. ': invalid regex match' );
664 if ( $startPos < $length ) {
665 $inner .= substr( $text, $startPos );
668 return '-{' . $this->autoConvert( $inner, $variant );
672 * If a language supports multiple variants, it is
673 * possible that non-existing link in one variant
674 * actually exists in another variant. This function
675 * tries to find it. See e.g. LanguageZh.php
677 * @param $link String: the name of the link
678 * @param $nt Mixed: the title object of the link
679 * @param $ignoreOtherCond Boolean: to disable other conditions when
680 * we need to transclude a template or update a category's link
681 * @return Null, the input parameters may be modified upon return
683 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
684 # If the article has already existed, there is no need to
685 # check it again, otherwise it may cause a fault.
686 if ( is_object( $nt ) && $nt->exists() ) {
690 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
692 $isredir = $wgRequest->getText( 'redirect', 'yes' );
693 $action = $wgRequest->getText( 'action' );
694 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
695 $disableLinkConversion = $wgDisableLangConversion
696 ||
$wgDisableTitleConversion;
697 $linkBatch = new LinkBatch();
701 if ( $disableLinkConversion ||
702 ( !$ignoreOtherCond &&
705 ||
$action == 'submit'
706 ||
$linkconvert == 'no'
707 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
711 if ( is_object( $nt ) ) {
712 $ns = $nt->getNamespace();
715 $variants = $this->autoConvertToAllVariants( $link );
716 if ( !$variants ) { // give up
722 foreach ( $variants as $v ) {
724 $varnt = Title
::newFromText( $v, $ns );
725 if ( !is_null( $varnt ) ) {
726 $linkBatch->addObj( $varnt );
732 // fetch all variants in single query
733 $linkBatch->execute();
735 foreach ( $titles as $varnt ) {
736 if ( $varnt->getArticleID() > 0 ) {
738 $link = $varnt->getText();
745 * Returns language specific hash options.
747 public function getExtraHashOptions() {
748 $variant = $this->getPreferredVariant();
749 return '!' . $variant ;
753 * Load default conversion tables.
754 * This method must be implemented in derived class.
758 function loadDefaultTables() {
759 $name = get_class( $this );
760 wfDie( "Must implement loadDefaultTables() method in class $name" );
764 * Load conversion tables either from the cache or the disk.
767 function loadTables( $fromcache = true ) {
768 if ( $this->mTablesLoaded
) {
772 wfProfileIn( __METHOD__
);
773 $this->mTablesLoaded
= true;
774 $this->mTables
= false;
776 wfProfileIn( __METHOD__
. '-cache' );
777 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
778 wfProfileOut( __METHOD__
. '-cache' );
781 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
782 wfProfileIn( __METHOD__
. '-recache' );
783 // not in cache, or we need a fresh reload.
784 // we will first load the default tables
785 // then update them using things in MediaWiki:Zhconversiontable/*
786 $this->loadDefaultTables();
787 foreach ( $this->mVariants
as $var ) {
788 $cached = $this->parseCachedTable( $var );
789 $this->mTables
[$var]->mergeArray( $cached );
792 $this->postLoadTables();
793 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
795 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
796 wfProfileOut( __METHOD__
. '-recache' );
798 wfProfileOut( __METHOD__
);
802 * Hook for post processig after conversion tables are loaded.
805 function postLoadTables() { }
808 * Reload the conversion tables.
812 function reloadTables() {
813 if ( $this->mTables
) {
814 unset( $this->mTables
);
816 $this->mTablesLoaded
= false;
817 $this->loadTables( false );
822 * Parse the conversion table stored in the cache.
824 * The tables should be in blocks of the following form:
831 * To make the tables more manageable, subpages are allowed
832 * and will be parsed recursively if $recursive == true.
835 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
836 global $wgMessageCache;
837 static $parsed = array();
839 if ( !is_object( $wgMessageCache ) ) {
843 $key = 'Conversiontable/' . $code;
845 $key .= '/' . $subpage;
847 if ( array_key_exists( $key, $parsed ) ) {
851 if ( strpos( $code, '/' ) === false ) {
852 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
853 if ( $txt === false ) {
854 # FIXME: this method doesn't seem to be expecting
855 # this possible outcome...
856 $txt = '<Conversiontable>';
859 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
860 "Conversiontable/$code" );
861 if ( $title && $title->exists() ) {
862 $article = new Article( $title );
863 $txt = $article->getContents();
869 // get all subpage links of the form
870 // [[MediaWiki:conversiontable/zh-xx/...|...]]
871 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
873 $subs = StringUtils
::explode( '[[', $txt );
875 foreach ( $subs as $sub ) {
876 $link = explode( ']]', $sub, 2 );
877 if ( count( $link ) != 2 ) {
880 $b = explode( '|', $link[0], 2 );
881 $b = explode( '/', trim( $b[0] ), 3 );
882 if ( count( $b ) == 3 ) {
888 if ( $b[0] == $linkhead && $b[1] == $code ) {
889 $sublinks[] = $sublink;
893 // parse the mappings in this page
894 $blocks = StringUtils
::explode( '-{', $txt );
897 foreach ( $blocks as $block ) {
899 // Skip the part before the first -{
903 $mappings = explode( '}-', $block, 2 );
904 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
906 $table = StringUtils
::explode( ';', $stripped );
907 foreach ( $table as $t ) {
908 $m = explode( '=>', $t, 3 );
909 if ( count( $m ) != 2 )
911 // trim any trailling comments starting with '//'
912 $tt = explode( '//', $m[1], 2 );
913 $ret[trim( $m[0] )] = trim( $tt[0] );
916 $parsed[$key] = true;
918 // recursively parse the subpages
920 foreach ( $sublinks as $link ) {
921 $s = $this->parseCachedTable( $code, $link, $recursive );
922 $ret = array_merge( $ret, $s );
926 if ( $this->mUcfirst
) {
927 foreach ( $ret as $k => $v ) {
928 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
935 * Enclose a string with the "no conversion" tag. This is used by
936 * various functions in the Parser.
938 * @param $text String: text to be tagged for no conversion
939 * @param $noParse Unused (?)
940 * @return String: the tagged text
942 public function markNoConversion( $text, $noParse = false ) {
943 # don't mark if already marked
944 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
948 $ret = "-{R|$text}-";
953 * Convert the sorting key for category links. This should make different
954 * keys that are variants of each other map to the same key.
956 function convertCategoryKey( $key ) {
961 * Hook to refresh the cache of conversion tables when
962 * MediaWiki:conversiontable* is updated.
965 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
966 $iswatch, $section, $flags, $revision ) {
967 $titleobj = $article->getTitle();
968 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
969 $title = $titleobj->getDBkey();
970 $t = explode( '/', $title, 3 );
972 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
973 if ( $this->validateVariant( $t[1] ) ) {
974 $this->reloadTables();
982 * Armour rendered math against conversion.
983 * Wrap math into rawoutput -{R| math }- syntax.
985 public function armourMath( $text ) {
986 // convert '-{' and '}-' to '-{' and '}-' to prevent
987 // any unwanted markup appearing in the math image tag.
988 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
993 * Get the cached separator pattern for ConverterRule::parseRules()
995 function getVarSeparatorPattern() {
996 if ( is_null( $this->mVarSeparatorPattern
) ) {
997 // varsep_pattern for preg_split:
998 // text should be splited by ";" only if a valid variant
999 // name exist after the markup, for example:
1000 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1001 // <span style="font-size:120%;">yyy</span>;}-
1002 // we should split it as:
1004 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1005 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1009 foreach ( $this->mVariants
as $variant ) {
1010 // zh-hans:xxx;zh-hant:yyy
1011 $pat .= $variant . '\s*:|';
1012 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1013 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1016 $this->mVarSeparatorPattern
= $pat;
1018 return $this->mVarSeparatorPattern
;
1023 * Parser for rules of language conversion , parse rules in -{ }- tag.
1025 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1027 class ConverterRule
{
1028 var $mText; // original text in -{text}-
1029 var $mConverter; // LanguageConverter object
1030 var $mManualCodeError = '<strong class="error">code error!</strong>';
1031 var $mRuleDisplay = '';
1032 var $mRuleTitle = false;
1033 var $mRules = '';// string : the text of the rules
1034 var $mRulesAction = 'none';
1035 var $mFlags = array();
1036 var $mVariantFlags = array();
1037 var $mConvTable = array();
1038 var $mBidtable = array();// array of the translation in each variant
1039 var $mUnidtable = array();// array of the translation in each variant
1044 * @param $text String: the text between -{ and }-
1045 * @param $converter LanguageConverter object
1047 public function __construct( $text, $converter ) {
1048 $this->mText
= $text;
1049 $this->mConverter
= $converter;
1053 * Check if variants array in convert array.
1055 * @param $variants Array or string: variant language code
1056 * @return String: translated text
1058 public function getTextInBidtable( $variants ) {
1059 $variants = (array)$variants;
1063 foreach ( $variants as $variant ) {
1064 if ( isset( $this->mBidtable
[$variant] ) ) {
1065 return $this->mBidtable
[$variant];
1072 * Parse flags with syntax -{FLAG| ... }-
1075 function parseFlags() {
1076 $text = $this->mText
;
1078 $variantFlags = array();
1080 $sepPos = strpos( $text, '|' );
1081 if ( $sepPos !== false ) {
1082 $validFlags = $this->mConverter
->mFlags
;
1083 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1084 foreach ( $f as $ff ) {
1086 if ( isset( $validFlags[$ff] ) ) {
1087 $flags[$validFlags[$ff]] = true;
1090 $text = strval( substr( $text, $sepPos +
1 ) );
1095 } elseif ( isset( $flags['R'] ) ) {
1096 $flags = array( 'R' => true );// remove other flags
1097 } elseif ( isset( $flags['N'] ) ) {
1098 $flags = array( 'N' => true );// remove other flags
1099 } elseif ( isset( $flags['-'] ) ) {
1100 $flags = array( '-' => true );// remove other flags
1101 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1103 } elseif ( isset( $flags['H'] ) ) {
1104 // replace A flag, and remove other flags except T
1105 $temp = array( '+' => true, 'H' => true );
1106 if ( isset( $flags['T'] ) ) {
1109 if ( isset( $flags['D'] ) ) {
1114 if ( isset( $flags['A'] ) ) {
1118 if ( isset( $flags['D'] ) ) {
1119 unset( $flags['S'] );
1121 // try to find flags like "zh-hans", "zh-hant"
1122 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1123 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1124 if ( $variantFlags ) {
1125 $variantFlags = array_flip( $variantFlags );
1129 $this->mVariantFlags
= $variantFlags;
1130 $this->mRules
= $text;
1131 $this->mFlags
= $flags;
1135 * Generate conversion table.
1138 function parseRules() {
1139 $rules = $this->mRules
;
1140 $bidtable = array();
1141 $unidtable = array();
1142 $variants = $this->mConverter
->mVariants
;
1143 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1145 $choice = preg_split( $varsep_pattern, $rules );
1147 foreach ( $choice as $c ) {
1148 $v = explode( ':', $c, 2 );
1149 if ( count( $v ) != 2 ) {
1150 // syntax error, skip
1153 $to = trim( $v[1] );
1155 $u = explode( '=>', $v, 2 );
1156 // if $to is empty, strtr() could return a wrong result
1157 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1158 $bidtable[$v] = $to;
1159 } elseif ( count( $u ) == 2 ) {
1160 $from = trim( $u[0] );
1162 if ( array_key_exists( $v, $unidtable )
1163 && !is_array( $unidtable[$v] )
1165 && in_array( $v, $variants ) ) {
1166 $unidtable[$v] = array( $from => $to );
1167 } elseif ( $to && in_array( $v, $variants ) ) {
1168 $unidtable[$v][$from] = $to;
1171 // syntax error, pass
1172 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1173 $bidtable = array();
1174 $unidtable = array();
1178 $this->mBidtable
= $bidtable;
1179 $this->mUnidtable
= $unidtable;
1185 function getRulesDesc() {
1186 $codesep = $this->mConverter
->mDescCodeSep
;
1187 $varsep = $this->mConverter
->mDescVarSep
;
1189 foreach ( $this->mBidtable
as $k => $v ) {
1190 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1192 foreach ( $this->mUnidtable
as $k => $a ) {
1193 foreach ( $a as $from => $to ) {
1194 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1195 "$codesep$to$varsep";
1202 * Parse rules conversion.
1205 function getRuleConvertedStr( $variant ) {
1206 $bidtable = $this->mBidtable
;
1207 $unidtable = $this->mUnidtable
;
1209 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1210 return $this->mRules
;
1212 // display current variant in bidirectional array
1213 $disp = $this->getTextInBidtable( $variant );
1214 // or display current variant in fallbacks
1216 $disp = $this->getTextInBidtable(
1217 $this->mConverter
->getVariantFallbacks( $variant ) );
1219 // or display current variant in unidirectional array
1220 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1221 $disp = array_values( $unidtable[$variant] );
1224 // or display frist text under disable manual convert
1226 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1227 if ( count( $bidtable ) > 0 ) {
1228 $disp = array_values( $bidtable );
1231 $disp = array_values( $unidtable );
1232 $disp = array_values( $disp[0] );
1241 * Generate conversion table for all text.
1244 function generateConvTable() {
1245 // Special case optimisation
1246 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1247 $this->mConvTable
= array();
1251 $bidtable = $this->mBidtable
;
1252 $unidtable = $this->mUnidtable
;
1253 $manLevel = $this->mConverter
->mManualLevel
;
1256 foreach ( $this->mConverter
->mVariants
as $v ) {
1257 /* for bidirectional array
1258 fill in the missing variants, if any,
1260 if ( !isset( $bidtable[$v] ) ) {
1262 $this->mConverter
->getVariantFallbacks( $v );
1263 $vf = $this->getTextInBidtable( $variantFallbacks );
1265 $bidtable[$v] = $vf;
1269 if ( isset( $bidtable[$v] ) ) {
1270 foreach ( $vmarked as $vo ) {
1271 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1272 // or -{H|zh:WordZh;zh-tw:WordTw}-
1273 // or -{-|zh:WordZh;zh-tw:WordTw}-
1274 // to introduce a custom mapping between
1275 // words WordZh and WordTw in the whole text
1276 if ( $manLevel[$v] == 'bidirectional' ) {
1277 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1279 if ( $manLevel[$vo] == 'bidirectional' ) {
1280 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1285 /*for unidirectional array fill to convert tables */
1286 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1287 && isset( $unidtable[$v] ) )
1289 if ( isset( $this->mConvTable
[$v] ) ) {
1290 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1292 $this->mConvTable
[$v] = $unidtable[$v];
1299 * Parse rules and flags.
1302 function parse( $variant = NULL ) {
1304 $variant = $this->mConverter
->getPreferredVariant();
1307 $this->parseFlags();
1308 $flags = $this->mFlags
;
1310 // convert to specified variant
1311 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1312 if ( $this->mVariantFlags
) {
1313 // check if current variant in flags
1314 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1315 // then convert <text to convert> to current language
1316 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1318 } else { // if current variant no in flags,
1319 // then we check its fallback variants.
1321 $this->mConverter
->getVariantFallbacks( $variant );
1322 foreach ( $variantFallbacks as $variantFallback ) {
1323 // if current variant's fallback exist in flags
1324 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1325 // then convert <text to convert> to fallback language
1327 $this->mConverter
->autoConvert( $this->mRules
,
1333 $this->mFlags
= $flags = array( 'R' => true );
1336 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1337 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1338 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1339 $this->parseRules();
1341 $rules = $this->mRules
;
1343 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1344 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1345 // fill all variants if text in -{A/H/-|text} without rules
1346 foreach ( $this->mConverter
->mVariants
as $v ) {
1347 $this->mBidtable
[$v] = $rules;
1349 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1350 $this->mFlags
= $flags = array( 'R' => true );
1354 $this->mRuleDisplay
= false;
1355 foreach ( $flags as $flag => $unused ) {
1358 // if we don't do content convert, still strip the -{}- tags
1359 $this->mRuleDisplay
= $rules;
1362 // process N flag: output current variant name
1363 $ruleVar = trim( $rules );
1364 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1365 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1367 $this->mRuleDisplay
= '';
1371 // process D flag: output rules description
1372 $this->mRuleDisplay
= $this->getRulesDesc();
1375 // process H,- flag or T only: output nothing
1376 $this->mRuleDisplay
= '';
1379 $this->mRulesAction
= 'remove';
1380 $this->mRuleDisplay
= '';
1383 $this->mRulesAction
= 'add';
1384 $this->mRuleDisplay
= '';
1387 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1390 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1391 $this->mRuleDisplay
= '';
1394 // ignore unknown flags (but see error case below)
1397 if ( $this->mRuleDisplay
=== false ) {
1398 $this->mRuleDisplay
= $this->mManualCodeError
;
1401 $this->generateConvTable();
1407 function hasRules() {
1412 * Get display text on markup -{...}-
1415 function getDisplay() {
1416 return $this->mRuleDisplay
;
1420 * Get converted title.
1423 function getTitle() {
1424 return $this->mRuleTitle
;
1428 * Return how deal with conversion rules.
1431 function getRulesAction() {
1432 return $this->mRulesAction
;
1436 * Get conversion table. ( bidirectional and unidirectional
1437 * conversion table )
1440 function getConvTable() {
1441 return $this->mConvTable
;
1445 * Get conversion rules string.
1448 function getRules() {
1449 return $this->mRules
;
1453 * Get conversion flags.
1456 function getFlags() {
1457 return $this->mFlags
;