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();
352 /* we convert everything except:
353 1. html markups (anything between < and >)
355 3. place holders created by the parser
358 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
359 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
364 // this one is needed when the text is inside an html markup
365 $htmlfix = '|<[^>]+$|^[^<>]*>';
367 // disable convert to variants between <code></code> tags
368 $codefix = '<code>.+?<\/code>|';
369 // disable convertsion of <script type="text/javascript"> ... </script>
370 $scriptfix = '<script.*?>.*?<\/script>|';
371 // disable conversion of <pre xxxx> ... </pre>
372 $prefix = '<pre.*?>.*?<\/pre>|';
374 $reg = '/' . $codefix . $scriptfix . $prefix .
375 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
377 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
379 $m = array_shift( $matches );
381 $ret = $this->translate( $m[0], $toVariant );
382 $mstart = $m[1] +
strlen( $m[0] );
384 // enable convertsion of '<img alt="xxxx" ... '
385 // or '<span title="xxxx" ... '
386 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
391 foreach ( $matches as $m ) {
392 $mark = substr( $text, $mstart, $m[1] - $mstart );
393 $mark = preg_replace_callback( $captionpattern,
394 array( &$this, 'captionConvert' ),
396 // Let's convert the trtext only once,
397 // it would give us more performance improvement
399 $trtext .= $m[0] . $trtextmark;
400 $mstart = $m[1] +
strlen( $m[0] );
403 $trtext = $this->translate( $trtext, $toVariant );
404 $trtext = StringUtils
::explode( $trtextmark, $trtext );
405 foreach ( $trtext as $t ) {
406 $ret .= array_shift( $notrtext );
409 wfProfileOut( __METHOD__
);
414 * Translate a string to a variant.
415 * Doesn't parse rules or do any of that other stuff, for that use
416 * convert() or convertTo().
418 * @param $text String: text to convert
419 * @param $variant String: variant language code
420 * @return String: translated text
422 protected function translate( $text, $variant ) {
423 wfProfileIn( __METHOD__
);
424 // If $text is empty or only includes spaces, do nothing
425 // Otherwise translate it
426 if ( trim( $text ) ) {
428 $text = $this->mTables
[$variant]->replace( $text );
430 wfProfileOut( __METHOD__
);
435 * Call translate() to convert text to all valid variants.
437 * @param $text String: the text to be converted
438 * @return Array: variant => converted text
440 public function autoConvertToAllVariants( $text ) {
441 wfProfileIn( __METHOD__
);
445 foreach ( $this->mVariants
as $variant ) {
446 $ret[$variant] = $this->translate( $text, $variant );
449 wfProfileOut( __METHOD__
);
454 * Convert link text to all valid variants.
455 * In the first, this function only convert text outside the
456 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
457 * titles, the text will get all converted always.
458 * So I removed this feature and deprecated the function.
460 * @param $text String: the text to be converted
461 * @return Array: variant => converted text
462 * @deprecated Use autoConvertToAllVariants() instead
464 public function convertLinkToAllVariants( $text ) {
465 return $this->autoConvertToAllVariants( $text );
469 * Apply manual conversion rules.
471 * @param $convRule Object: Object of ConverterRule
473 protected function applyManualConv( $convRule ) {
474 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
476 // Bug 24072: $mConvRuleTitle was overwritten by other manual
477 // rule(s) not for title, this breaks the title conversion.
478 $newConvRuleTitle = $convRule->getTitle();
479 if ( $newConvRuleTitle ) {
480 // So I add an empty check for getTitle()
481 $this->mConvRuleTitle
= $newConvRuleTitle;
484 // merge/remove manual conversion rules to/from global table
485 $convTable = $convRule->getConvTable();
486 $action = $convRule->getRulesAction();
487 foreach ( $convTable as $variant => $pair ) {
488 if ( !$this->validateVariant( $variant ) ) {
492 if ( $action == 'add' ) {
493 foreach ( $pair as $from => $to ) {
494 // to ensure that $from and $to not be left blank
495 // so $this->translate() could always return a string
496 if ( $from ||
$to ) {
497 // more efficient than array_merge(), about 2.5 times.
498 $this->mTables
[$variant]->setPair( $from, $to );
501 } elseif ( $action == 'remove' ) {
502 $this->mTables
[$variant]->removeArray( $pair );
508 * Auto convert a Title object to a readable string in the
511 *@param $title Object: a object of Title
512 *@return String: converted title text
514 public function convertTitle( $title ) {
515 $variant = $this->getPreferredVariant();
516 $index = $title->getNamespace();
517 if ( $index === NS_MAIN
) {
520 // first let's check if a message has given us a converted name
521 $nsConvKey = 'conversion-ns' . $index;
522 if ( !wfEmptyMsg( $nsConvKey ) ) {
523 $text = wfMsgForContentNoTrans( $nsConvKey );
525 // the message does not exist, try retrieve it from the current
526 // variant's namespace names.
527 $langObj = $this->mLangObj
->factory( $variant );
528 $text = $langObj->getFormattedNsText( $index );
532 $text .= $title->getText();
533 $text = $this->translate( $text, $variant );
538 * Convert text to different variants of a language. The automatic
539 * conversion is done in autoConvert(). Here we parse the text
540 * marked with -{}-, which specifies special conversions of the
541 * text that can not be accomplished in autoConvert().
543 * Syntax of the markup:
544 * -{code1:text1;code2:text2;...}- or
545 * -{flags|code1:text1;code2:text2;...}- or
546 * -{text}- in which case no conversion should take place for text
548 * @param $text String: text to be converted
549 * @return String: converted text
551 public function convert( $text ) {
552 $variant = $this->getPreferredVariant();
553 return $this->convertTo( $text, $variant );
557 * Same as convert() except a extra parameter to custom variant.
559 * @param $text String: text to be converted
560 * @param $variant String: the target variant code
561 * @return String: converted text
563 public function convertTo( $text, $variant ) {
564 global $wgDisableLangConversion;
565 if ( $wgDisableLangConversion ) return $text;
566 return $this->recursiveConvertTopLevel( $text, $variant );
570 * Recursively convert text on the outside. Allow to use nested
571 * markups to custom rules.
573 * @param $text String: text to be converted
574 * @param $variant String: the target variant code
575 * @param $depth Integer: depth of recursion
576 * @return String: converted text
578 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
581 $length = strlen( $text );
582 while ( $startPos < $length ) {
583 $pos = strpos( $text, '-{', $startPos );
585 if ( $pos === false ) {
586 // No more markup, append final segment
587 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
592 // Append initial segment
593 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
598 // Do recursive conversion
599 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
606 * Recursively convert text on the inside.
608 * @param $text String: text to be converted
609 * @param $variant String: the target variant code
610 * @param $depth Integer: depth of recursion
611 * @return String: converted text
613 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
614 // Quick sanity check (no function calls)
615 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
616 throw new MWException( __METHOD__
. ': invalid input string' );
621 $warningDone = false;
622 $length = strlen( $text );
624 while ( $startPos < $length ) {
626 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
636 // Append initial segment
637 $inner .= substr( $text, $startPos, $pos - $startPos );
645 if ( $depth >= $this->mMaxDepth
) {
647 if ( !$warningDone ) {
648 $inner .= '<span class="error">' .
649 wfMsgForContent( 'language-converter-depth-warning',
657 // Recursively parse another rule
658 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
663 $rule = new ConverterRule( $inner, $this );
664 $rule->parse( $variant );
665 $this->applyManualConv( $rule );
666 return $rule->getDisplay();
668 throw new MWException( __METHOD__
. ': invalid regex match' );
673 if ( $startPos < $length ) {
674 $inner .= substr( $text, $startPos );
677 return '-{' . $this->autoConvert( $inner, $variant );
681 * If a language supports multiple variants, it is
682 * possible that non-existing link in one variant
683 * actually exists in another variant. This function
684 * tries to find it. See e.g. LanguageZh.php
686 * @param $link String: the name of the link
687 * @param $nt Mixed: the title object of the link
688 * @param $ignoreOtherCond Boolean: to disable other conditions when
689 * we need to transclude a template or update a category's link
690 * @return Null, the input parameters may be modified upon return
692 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
693 # If the article has already existed, there is no need to
694 # check it again, otherwise it may cause a fault.
695 if ( is_object( $nt ) && $nt->exists() ) {
699 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
701 $isredir = $wgRequest->getText( 'redirect', 'yes' );
702 $action = $wgRequest->getText( 'action' );
703 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
704 $disableLinkConversion = $wgDisableLangConversion
705 ||
$wgDisableTitleConversion;
706 $linkBatch = new LinkBatch();
710 if ( $disableLinkConversion ||
711 ( !$ignoreOtherCond &&
714 ||
$action == 'submit'
715 ||
$linkconvert == 'no'
716 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
720 if ( is_object( $nt ) ) {
721 $ns = $nt->getNamespace();
724 $variants = $this->autoConvertToAllVariants( $link );
725 if ( !$variants ) { // give up
731 foreach ( $variants as $v ) {
733 $varnt = Title
::newFromText( $v, $ns );
734 if ( !is_null( $varnt ) ) {
735 $linkBatch->addObj( $varnt );
741 // fetch all variants in single query
742 $linkBatch->execute();
744 foreach ( $titles as $varnt ) {
745 if ( $varnt->getArticleID() > 0 ) {
747 $link = $varnt->getText();
754 * Returns language specific hash options.
756 public function getExtraHashOptions() {
757 $variant = $this->getPreferredVariant();
758 return '!' . $variant ;
762 * Load default conversion tables.
763 * This method must be implemented in derived class.
767 function loadDefaultTables() {
768 $name = get_class( $this );
769 wfDie( "Must implement loadDefaultTables() method in class $name" );
773 * Load conversion tables either from the cache or the disk.
776 function loadTables( $fromcache = true ) {
777 if ( $this->mTablesLoaded
) {
781 wfProfileIn( __METHOD__
);
782 $this->mTablesLoaded
= true;
783 $this->mTables
= false;
785 wfProfileIn( __METHOD__
. '-cache' );
786 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
787 wfProfileOut( __METHOD__
. '-cache' );
790 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
791 wfProfileIn( __METHOD__
. '-recache' );
792 // not in cache, or we need a fresh reload.
793 // we will first load the default tables
794 // then update them using things in MediaWiki:Zhconversiontable/*
795 $this->loadDefaultTables();
796 foreach ( $this->mVariants
as $var ) {
797 $cached = $this->parseCachedTable( $var );
798 $this->mTables
[$var]->mergeArray( $cached );
801 $this->postLoadTables();
802 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
804 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
805 wfProfileOut( __METHOD__
. '-recache' );
807 wfProfileOut( __METHOD__
);
811 * Hook for post processig after conversion tables are loaded.
814 function postLoadTables() { }
817 * Reload the conversion tables.
821 function reloadTables() {
822 if ( $this->mTables
) {
823 unset( $this->mTables
);
825 $this->mTablesLoaded
= false;
826 $this->loadTables( false );
831 * Parse the conversion table stored in the cache.
833 * The tables should be in blocks of the following form:
840 * To make the tables more manageable, subpages are allowed
841 * and will be parsed recursively if $recursive == true.
844 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
845 static $parsed = array();
847 $key = 'Conversiontable/' . $code;
849 $key .= '/' . $subpage;
851 if ( array_key_exists( $key, $parsed ) ) {
855 if ( strpos( $code, '/' ) === false ) {
856 $txt = MessageCache
::singleton()->get( 'Conversiontable', true, $code );
857 if ( $txt === false ) {
858 # FIXME: this method doesn't seem to be expecting
859 # this possible outcome...
860 $txt = '<Conversiontable>';
863 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
864 "Conversiontable/$code" );
865 if ( $title && $title->exists() ) {
866 $article = new Article( $title );
867 $txt = $article->getContents();
873 // get all subpage links of the form
874 // [[MediaWiki:conversiontable/zh-xx/...|...]]
875 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
877 $subs = StringUtils
::explode( '[[', $txt );
879 foreach ( $subs as $sub ) {
880 $link = explode( ']]', $sub, 2 );
881 if ( count( $link ) != 2 ) {
884 $b = explode( '|', $link[0], 2 );
885 $b = explode( '/', trim( $b[0] ), 3 );
886 if ( count( $b ) == 3 ) {
892 if ( $b[0] == $linkhead && $b[1] == $code ) {
893 $sublinks[] = $sublink;
897 // parse the mappings in this page
898 $blocks = StringUtils
::explode( '-{', $txt );
901 foreach ( $blocks as $block ) {
903 // Skip the part before the first -{
907 $mappings = explode( '}-', $block, 2 );
908 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
910 $table = StringUtils
::explode( ';', $stripped );
911 foreach ( $table as $t ) {
912 $m = explode( '=>', $t, 3 );
913 if ( count( $m ) != 2 )
915 // trim any trailling comments starting with '//'
916 $tt = explode( '//', $m[1], 2 );
917 $ret[trim( $m[0] )] = trim( $tt[0] );
920 $parsed[$key] = true;
922 // recursively parse the subpages
924 foreach ( $sublinks as $link ) {
925 $s = $this->parseCachedTable( $code, $link, $recursive );
926 $ret = array_merge( $ret, $s );
930 if ( $this->mUcfirst
) {
931 foreach ( $ret as $k => $v ) {
932 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
939 * Enclose a string with the "no conversion" tag. This is used by
940 * various functions in the Parser.
942 * @param $text String: text to be tagged for no conversion
943 * @param $noParse Unused (?)
944 * @return String: the tagged text
946 public function markNoConversion( $text, $noParse = false ) {
947 # don't mark if already marked
948 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
952 $ret = "-{R|$text}-";
957 * Convert the sorting key for category links. This should make different
958 * keys that are variants of each other map to the same key.
960 function convertCategoryKey( $key ) {
965 * Hook to refresh the cache of conversion tables when
966 * MediaWiki:conversiontable* is updated.
969 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
970 $iswatch, $section, $flags, $revision ) {
971 $titleobj = $article->getTitle();
972 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
973 $title = $titleobj->getDBkey();
974 $t = explode( '/', $title, 3 );
976 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
977 if ( $this->validateVariant( $t[1] ) ) {
978 $this->reloadTables();
986 * Armour rendered math against conversion.
987 * Escape special chars in parsed math text.(in most cases are img elements)
989 public function armourMath( $text ) {
990 // convert '-{' and '}-' to '-{' and '}-' to prevent
991 // any unwanted markup appearing in the math image tag.
992 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
997 * Get the cached separator pattern for ConverterRule::parseRules()
999 function getVarSeparatorPattern() {
1000 if ( is_null( $this->mVarSeparatorPattern
) ) {
1001 // varsep_pattern for preg_split:
1002 // text should be splited by ";" only if a valid variant
1003 // name exist after the markup, for example:
1004 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1005 // <span style="font-size:120%;">yyy</span>;}-
1006 // we should split it as:
1008 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1009 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1013 foreach ( $this->mVariants
as $variant ) {
1014 // zh-hans:xxx;zh-hant:yyy
1015 $pat .= $variant . '\s*:|';
1016 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1017 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1020 $this->mVarSeparatorPattern
= $pat;
1022 return $this->mVarSeparatorPattern
;
1027 * Parser for rules of language conversion , parse rules in -{ }- tag.
1029 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1031 class ConverterRule
{
1032 var $mText; // original text in -{text}-
1033 var $mConverter; // LanguageConverter object
1034 var $mManualCodeError = '<strong class="error">code error!</strong>';
1035 var $mRuleDisplay = '';
1036 var $mRuleTitle = false;
1037 var $mRules = '';// string : the text of the rules
1038 var $mRulesAction = 'none';
1039 var $mFlags = array();
1040 var $mVariantFlags = array();
1041 var $mConvTable = array();
1042 var $mBidtable = array();// array of the translation in each variant
1043 var $mUnidtable = array();// array of the translation in each variant
1048 * @param $text String: the text between -{ and }-
1049 * @param $converter LanguageConverter object
1051 public function __construct( $text, $converter ) {
1052 $this->mText
= $text;
1053 $this->mConverter
= $converter;
1057 * Check if variants array in convert array.
1059 * @param $variants Array or string: variant language code
1060 * @return String: translated text
1062 public function getTextInBidtable( $variants ) {
1063 $variants = (array)$variants;
1067 foreach ( $variants as $variant ) {
1068 if ( isset( $this->mBidtable
[$variant] ) ) {
1069 return $this->mBidtable
[$variant];
1076 * Parse flags with syntax -{FLAG| ... }-
1079 function parseFlags() {
1080 $text = $this->mText
;
1082 $variantFlags = array();
1084 $sepPos = strpos( $text, '|' );
1085 if ( $sepPos !== false ) {
1086 $validFlags = $this->mConverter
->mFlags
;
1087 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1088 foreach ( $f as $ff ) {
1090 if ( isset( $validFlags[$ff] ) ) {
1091 $flags[$validFlags[$ff]] = true;
1094 $text = strval( substr( $text, $sepPos +
1 ) );
1099 } elseif ( isset( $flags['R'] ) ) {
1100 $flags = array( 'R' => true );// remove other flags
1101 } elseif ( isset( $flags['N'] ) ) {
1102 $flags = array( 'N' => true );// remove other flags
1103 } elseif ( isset( $flags['-'] ) ) {
1104 $flags = array( '-' => true );// remove other flags
1105 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1107 } elseif ( isset( $flags['H'] ) ) {
1108 // replace A flag, and remove other flags except T
1109 $temp = array( '+' => true, 'H' => true );
1110 if ( isset( $flags['T'] ) ) {
1113 if ( isset( $flags['D'] ) ) {
1118 if ( isset( $flags['A'] ) ) {
1122 if ( isset( $flags['D'] ) ) {
1123 unset( $flags['S'] );
1125 // try to find flags like "zh-hans", "zh-hant"
1126 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1127 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1128 if ( $variantFlags ) {
1129 $variantFlags = array_flip( $variantFlags );
1133 $this->mVariantFlags
= $variantFlags;
1134 $this->mRules
= $text;
1135 $this->mFlags
= $flags;
1139 * Generate conversion table.
1142 function parseRules() {
1143 $rules = $this->mRules
;
1144 $bidtable = array();
1145 $unidtable = array();
1146 $variants = $this->mConverter
->mVariants
;
1147 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1149 $choice = preg_split( $varsep_pattern, $rules );
1151 foreach ( $choice as $c ) {
1152 $v = explode( ':', $c, 2 );
1153 if ( count( $v ) != 2 ) {
1154 // syntax error, skip
1157 $to = trim( $v[1] );
1159 $u = explode( '=>', $v, 2 );
1160 // if $to is empty, strtr() could return a wrong result
1161 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1162 $bidtable[$v] = $to;
1163 } elseif ( count( $u ) == 2 ) {
1164 $from = trim( $u[0] );
1166 if ( array_key_exists( $v, $unidtable )
1167 && !is_array( $unidtable[$v] )
1169 && in_array( $v, $variants ) ) {
1170 $unidtable[$v] = array( $from => $to );
1171 } elseif ( $to && in_array( $v, $variants ) ) {
1172 $unidtable[$v][$from] = $to;
1175 // syntax error, pass
1176 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1177 $bidtable = array();
1178 $unidtable = array();
1182 $this->mBidtable
= $bidtable;
1183 $this->mUnidtable
= $unidtable;
1189 function getRulesDesc() {
1190 $codesep = $this->mConverter
->mDescCodeSep
;
1191 $varsep = $this->mConverter
->mDescVarSep
;
1193 foreach ( $this->mBidtable
as $k => $v ) {
1194 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1196 foreach ( $this->mUnidtable
as $k => $a ) {
1197 foreach ( $a as $from => $to ) {
1198 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1199 "$codesep$to$varsep";
1206 * Parse rules conversion.
1209 function getRuleConvertedStr( $variant ) {
1210 $bidtable = $this->mBidtable
;
1211 $unidtable = $this->mUnidtable
;
1213 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1214 return $this->mRules
;
1216 // display current variant in bidirectional array
1217 $disp = $this->getTextInBidtable( $variant );
1218 // or display current variant in fallbacks
1220 $disp = $this->getTextInBidtable(
1221 $this->mConverter
->getVariantFallbacks( $variant ) );
1223 // or display current variant in unidirectional array
1224 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1225 $disp = array_values( $unidtable[$variant] );
1228 // or display frist text under disable manual convert
1230 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1231 if ( count( $bidtable ) > 0 ) {
1232 $disp = array_values( $bidtable );
1235 $disp = array_values( $unidtable );
1236 $disp = array_values( $disp[0] );
1245 * Generate conversion table for all text.
1248 function generateConvTable() {
1249 // Special case optimisation
1250 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1251 $this->mConvTable
= array();
1255 $bidtable = $this->mBidtable
;
1256 $unidtable = $this->mUnidtable
;
1257 $manLevel = $this->mConverter
->mManualLevel
;
1260 foreach ( $this->mConverter
->mVariants
as $v ) {
1261 /* for bidirectional array
1262 fill in the missing variants, if any,
1264 if ( !isset( $bidtable[$v] ) ) {
1266 $this->mConverter
->getVariantFallbacks( $v );
1267 $vf = $this->getTextInBidtable( $variantFallbacks );
1269 $bidtable[$v] = $vf;
1273 if ( isset( $bidtable[$v] ) ) {
1274 foreach ( $vmarked as $vo ) {
1275 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1276 // or -{H|zh:WordZh;zh-tw:WordTw}-
1277 // or -{-|zh:WordZh;zh-tw:WordTw}-
1278 // to introduce a custom mapping between
1279 // words WordZh and WordTw in the whole text
1280 if ( $manLevel[$v] == 'bidirectional' ) {
1281 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1283 if ( $manLevel[$vo] == 'bidirectional' ) {
1284 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1289 /*for unidirectional array fill to convert tables */
1290 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1291 && isset( $unidtable[$v] ) )
1293 if ( isset( $this->mConvTable
[$v] ) ) {
1294 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1296 $this->mConvTable
[$v] = $unidtable[$v];
1303 * Parse rules and flags.
1306 function parse( $variant = NULL ) {
1308 $variant = $this->mConverter
->getPreferredVariant();
1311 $this->parseFlags();
1312 $flags = $this->mFlags
;
1314 // convert to specified variant
1315 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1316 if ( $this->mVariantFlags
) {
1317 // check if current variant in flags
1318 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1319 // then convert <text to convert> to current language
1320 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1322 } else { // if current variant no in flags,
1323 // then we check its fallback variants.
1325 $this->mConverter
->getVariantFallbacks( $variant );
1326 foreach ( $variantFallbacks as $variantFallback ) {
1327 // if current variant's fallback exist in flags
1328 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1329 // then convert <text to convert> to fallback language
1331 $this->mConverter
->autoConvert( $this->mRules
,
1337 $this->mFlags
= $flags = array( 'R' => true );
1340 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1341 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1342 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1343 $this->parseRules();
1345 $rules = $this->mRules
;
1347 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1348 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1349 // fill all variants if text in -{A/H/-|text} without rules
1350 foreach ( $this->mConverter
->mVariants
as $v ) {
1351 $this->mBidtable
[$v] = $rules;
1353 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1354 $this->mFlags
= $flags = array( 'R' => true );
1358 $this->mRuleDisplay
= false;
1359 foreach ( $flags as $flag => $unused ) {
1362 // if we don't do content convert, still strip the -{}- tags
1363 $this->mRuleDisplay
= $rules;
1366 // process N flag: output current variant name
1367 $ruleVar = trim( $rules );
1368 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1369 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1371 $this->mRuleDisplay
= '';
1375 // process D flag: output rules description
1376 $this->mRuleDisplay
= $this->getRulesDesc();
1379 // process H,- flag or T only: output nothing
1380 $this->mRuleDisplay
= '';
1383 $this->mRulesAction
= 'remove';
1384 $this->mRuleDisplay
= '';
1387 $this->mRulesAction
= 'add';
1388 $this->mRuleDisplay
= '';
1391 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1394 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1395 $this->mRuleDisplay
= '';
1398 // ignore unknown flags (but see error case below)
1401 if ( $this->mRuleDisplay
=== false ) {
1402 $this->mRuleDisplay
= $this->mManualCodeError
;
1405 $this->generateConvTable();
1411 function hasRules() {
1416 * Get display text on markup -{...}-
1419 function getDisplay() {
1420 return $this->mRuleDisplay
;
1424 * Get converted title.
1427 function getTitle() {
1428 return $this->mRuleTitle
;
1432 * Return how deal with conversion rules.
1435 function getRulesAction() {
1436 return $this->mRulesAction
;
1440 * Get conversion table. ( bidirectional and unidirectional
1441 * conversion table )
1444 function getConvTable() {
1445 return $this->mConvTable
;
1449 * Get conversion rules string.
1452 function getRules() {
1453 return $this->mRules
;
1457 * Get conversion flags.
1460 function getFlags() {
1461 return $this->mFlags
;