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
40 * @var String: memcached key name
46 var $mDescCodeSep = ':', $mDescVarSep = ';';
47 var $mUcfirst = false;
48 var $mConvRuleTitle = false;
53 var $mVarSeparatorPattern;
55 const CACHE_VERSION_KEY
= 'VERSION 6';
60 * @param $langobj Language: the Language Object
61 * @param $maincode String: the main language code of this language
62 * @param $variants Array: the supported variants of this language
63 * @param $variantfallbacks Array: the fallback language of each variant
64 * @param $flags Array: defining the custom strings that maps to the flags
65 * @param $manualLevel Array: limit for supported variants
67 public function __construct( $langobj, $maincode, $variants = array(),
68 $variantfallbacks = array(), $flags = array(),
69 $manualLevel = array() ) {
70 global $wgDisabledVariants;
71 $this->mLangObj
= $langobj;
72 $this->mMainLanguageCode
= $maincode;
73 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
74 $this->mVariantFallbacks
= $variantfallbacks;
75 $this->mVariantNames
= Language
::getLanguageNames();
76 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
77 $defaultflags = array(
78 // 'S' show converted text
79 // '+' add rules for alltext
80 // 'E' the gave flags is error
81 // these flags above are reserved for program
82 'A' => 'A', // add rule for convert code (all text convert)
83 'T' => 'T', // title convert
84 'R' => 'R', // raw content
85 'D' => 'D', // convert description (subclass implement)
86 '-' => '-', // remove convert (not implement)
87 'H' => 'H', // add rule for convert code
88 // (but no display in placed code)
89 'N' => 'N' // current variant name
91 $this->mFlags
= array_merge( $defaultflags, $flags );
92 foreach ( $this->mVariants
as $v ) {
93 if ( array_key_exists( $v, $manualLevel ) ) {
94 $this->mManualLevel
[$v] = $manualLevel[$v];
96 $this->mManualLevel
[$v] = 'bidirectional';
98 $this->mFlags
[$v] = $v;
103 * Get all valid variants.
104 * Call this instead of using $this->mVariants directly.
106 * @return Array: contains all valid variants
108 public function getVariants() {
109 return $this->mVariants
;
113 * In case some variant is not defined in the markup, we need
114 * to have some fallback. For example, in zh, normally people
115 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
116 * when zh-sg is preferred but not defined, we will pick zh-hans
117 * in this case. Right now this is only used by zh.
119 * @param $variant String: the language code of the variant
120 * @return String: The code of the fallback language or the
121 * main code if there is no fallback
123 public function getVariantFallbacks( $variant ) {
124 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
125 return $this->mVariantFallbacks
[$variant];
127 return $this->mMainLanguageCode
;
131 * Get the title produced by the conversion rule.
132 * @return String: The converted title text
134 public function getConvRuleTitle() {
135 return $this->mConvRuleTitle
;
139 * Get preferred language variant.
140 * @return String: the preferred language code
142 public function getPreferredVariant() {
143 global $wgDefaultLanguageVariant, $wgUser;
145 $req = $this->getURLVariant();
147 if ( $wgUser->isLoggedIn() && !$req ) {
148 $req = $this->getUserVariant();
150 $req = $this->getHeaderVariant();
153 if ( $wgDefaultLanguageVariant && !$req ) {
154 $req = $this->validateVariant( $wgDefaultLanguageVariant );
157 // This function, unlike the other get*Variant functions, is
158 // not memoized (i.e. there return value is not cached) since
159 // new information might appear during processing after this
164 return $this->mMainLanguageCode
;
168 * Get default variant.
169 * This function would not be affected by user's settings or headers
170 * @return String: the default variant code
172 public function getDefaultVariant() {
173 global $wgDefaultLanguageVariant;
175 $req = $this->getURLVariant();
177 if ( $wgDefaultLanguageVariant && !$req ) {
178 $req = $this->validateVariant( $wgDefaultLanguageVariant );
184 return $this->mMainLanguageCode
;
188 * Validate the variant
189 * @param $variant String: the variant to validate
190 * @return Mixed: returns the variant if it is valid, null otherwise
192 protected function validateVariant( $variant = null ) {
193 if ( $variant !== null && 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
231 if ( $this->mUserVariant ) {
232 return $this->mUserVariant;
236 // Get language variant preference from logged in users
237 // Don't call this on stub objects because that causes infinite
238 // recursion during initialisation
239 if ( $wgUser->isLoggedIn() ) {
240 $ret = $wgUser->getOption( 'variant' );
242 // figure out user lang without constructing wgLang to avoid
243 // infinite recursion
244 $ret = $wgUser->getOption( 'language' );
247 return $this->mUserVariant
= $this->validateVariant( $ret );
251 * Determine the language variant from the Accept-Language header.
253 * @return Mixed: variant if one found, false otherwise.
255 protected function getHeaderVariant() {
258 if ( $this->mHeaderVariant
) {
259 return $this->mHeaderVariant
;
262 // see if some supported language variant is set in the
264 $languages = array_keys( $wgRequest->getAcceptLang() );
265 if ( empty( $languages ) ) {
269 $fallbackLanguages = array();
270 foreach ( $languages as $language ) {
271 $this->mHeaderVariant
= $this->validateVariant( $language );
272 if ( $this->mHeaderVariant
) {
276 // To see if there are fallbacks of current language.
277 // We record these fallback variants, and process
279 $fallbacks = $this->getVariantFallbacks( $language );
280 if ( is_string( $fallbacks ) ) {
281 $fallbackLanguages[] = $fallbacks;
282 } elseif ( is_array( $fallbacks ) ) {
284 array_merge( $fallbackLanguages, $fallbacks );
288 if ( !$this->mHeaderVariant
) {
289 // process fallback languages now
290 $fallback_languages = array_unique( $fallbackLanguages );
291 foreach ( $fallback_languages as $language ) {
292 $this->mHeaderVariant
= $this->validateVariant( $language );
293 if ( $this->mHeaderVariant
) {
299 return $this->mHeaderVariant
;
303 * Dictionary-based conversion.
304 * This function would not parse the conversion rules.
305 * If you want to parse rules, try to use convert() or
308 * @param $text String the text to be converted
309 * @param $toVariant bool|string the target language code
310 * @return String the converted text
312 public function autoConvert( $text, $toVariant = false ) {
313 wfProfileIn( __METHOD__
);
318 $toVariant = $this->getPreferredVariant();
320 wfProfileOut( __METHOD__
);
325 /* we convert everything except:
326 1. HTML markups (anything between < and >)
328 3. placeholders created by the parser
331 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
332 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
337 // this one is needed when the text is inside an HTML markup
338 $htmlfix = '|<[^>]+$|^[^<>]*>';
340 // disable convert to variants between <code></code> tags
341 $codefix = '<code>.+?<\/code>|';
342 // disable convertsion of <script type="text/javascript"> ... </script>
343 $scriptfix = '<script.*?>.*?<\/script>|';
344 // disable conversion of <pre xxxx> ... </pre>
345 $prefix = '<pre.*?>.*?<\/pre>|';
347 $reg = '/' . $codefix . $scriptfix . $prefix .
348 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
353 // Guard against delimiter nulls in the input
354 $text = str_replace( "\000", '', $text );
356 $markupMatches = null;
357 $elementMatches = null;
358 while ( $startPos < strlen( $text ) ) {
359 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
360 $elementPos = $markupMatches[0][1];
361 $element = $markupMatches[0][0];
363 $elementPos = strlen( $text );
367 // Queue the part before the markup for translation in a batch
368 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
370 // Advance to the next position
371 $startPos = $elementPos +
strlen( $element );
373 // Translate any alt or title attributes inside the matched element
374 if ( $element !== '' && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element,
377 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
379 foreach ( array( 'title', 'alt' ) as $attrName ) {
380 if ( !isset( $attrs[$attrName] ) ) {
383 $attr = $attrs[$attrName];
384 // Don't convert URLs
385 if ( !strpos( $attr, '://' ) ) {
386 $attr = $this->translate( $attr, $toVariant );
389 // Remove HTML tags to avoid disrupting the layout
390 $attr = preg_replace( '/<[^>]+>/', '', $attr );
391 if ( $attr !== $attrs[$attrName] ) {
392 $attrs[$attrName] = $attr;
397 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
401 $literalBlob .= $element . "\000";
404 // Do the main translation batch
405 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
407 // Put the output back together
408 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
409 $literalIter = StringUtils
::explode( "\000", $literalBlob );
411 while ( $translatedIter->valid() && $literalIter->valid() ) {
412 $output .= $translatedIter->current();
413 $output .= $literalIter->current();
414 $translatedIter->next();
415 $literalIter->next();
418 wfProfileOut( __METHOD__
);
423 * Translate a string to a variant.
424 * Doesn't parse rules or do any of that other stuff, for that use
425 * convert() or convertTo().
427 * @param $text String: text to convert
428 * @param $variant String: variant language code
429 * @return String: translated text
431 public function translate( $text, $variant ) {
432 wfProfileIn( __METHOD__
);
433 // If $text is empty or only includes spaces, do nothing
434 // Otherwise translate it
435 if ( trim( $text ) ) {
437 $text = $this->mTables
[$variant]->replace( $text );
439 wfProfileOut( __METHOD__
);
444 * Call translate() to convert text to all valid variants.
446 * @param $text String: the text to be converted
447 * @return Array: variant => converted text
449 public function autoConvertToAllVariants( $text ) {
450 wfProfileIn( __METHOD__
);
454 foreach ( $this->mVariants
as $variant ) {
455 $ret[$variant] = $this->translate( $text, $variant );
458 wfProfileOut( __METHOD__
);
463 * Convert link text to all valid variants.
464 * In the first, this function only convert text outside the
465 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
466 * titles, the text will get all converted always.
467 * So I removed this feature and deprecated the function.
469 * @param $text String: the text to be converted
470 * @return Array: variant => converted text
471 * @deprecated since 1.17 Use autoConvertToAllVariants() instead
473 public function convertLinkToAllVariants( $text ) {
474 return $this->autoConvertToAllVariants( $text );
478 * Apply manual conversion rules.
480 * @param $convRule ConverterRule Object of ConverterRule
482 protected function applyManualConv( $convRule ) {
483 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
485 // Bug 24072: $mConvRuleTitle was overwritten by other manual
486 // rule(s) not for title, this breaks the title conversion.
487 $newConvRuleTitle = $convRule->getTitle();
488 if ( $newConvRuleTitle ) {
489 // So I add an empty check for getTitle()
490 $this->mConvRuleTitle
= $newConvRuleTitle;
493 // merge/remove manual conversion rules to/from global table
494 $convTable = $convRule->getConvTable();
495 $action = $convRule->getRulesAction();
496 foreach ( $convTable as $variant => $pair ) {
497 if ( !$this->validateVariant( $variant ) ) {
501 if ( $action == 'add' ) {
502 foreach ( $pair as $from => $to ) {
503 // to ensure that $from and $to not be left blank
504 // so $this->translate() could always return a string
505 if ( $from ||
$to ) {
506 // more efficient than array_merge(), about 2.5 times.
507 $this->mTables
[$variant]->setPair( $from, $to );
510 } elseif ( $action == 'remove' ) {
511 $this->mTables
[$variant]->removeArray( $pair );
517 * Auto convert a Title object to a readable string in the
520 * @param $title Title a object of Title
521 * @return String: converted title text
523 public function convertTitle( $title ) {
524 $variant = $this->getPreferredVariant();
525 $index = $title->getNamespace();
526 if ( $index === NS_MAIN
) {
529 // first let's check if a message has given us a converted name
530 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
531 if ( $nsConvMsg->exists() ) {
532 $text = $nsConvMsg->plain();
534 // the message does not exist, try retrieve it from the current
535 // variant's namespace names.
536 $langObj = $this->mLangObj
->factory( $variant );
537 $text = $langObj->getFormattedNsText( $index );
541 $text .= $title->getText();
542 $text = $this->translate( $text, $variant );
547 * Convert text to different variants of a language. The automatic
548 * conversion is done in autoConvert(). Here we parse the text
549 * marked with -{}-, which specifies special conversions of the
550 * text that can not be accomplished in autoConvert().
552 * Syntax of the markup:
553 * -{code1:text1;code2:text2;...}- or
554 * -{flags|code1:text1;code2:text2;...}- or
555 * -{text}- in which case no conversion should take place for text
557 * @param $text String: text to be converted
558 * @return String: converted text
560 public function convert( $text ) {
561 $variant = $this->getPreferredVariant();
562 return $this->convertTo( $text, $variant );
566 * Same as convert() except a extra parameter to custom variant.
568 * @param $text String: text to be converted
569 * @param $variant String: the target variant code
570 * @return String: converted text
572 public function convertTo( $text, $variant ) {
573 global $wgDisableLangConversion;
574 if ( $wgDisableLangConversion ) {
577 return $this->recursiveConvertTopLevel( $text, $variant );
581 * Recursively convert text on the outside. Allow to use nested
582 * markups to custom rules.
584 * @param $text String: text to be converted
585 * @param $variant String: the target variant code
586 * @param $depth Integer: depth of recursion
587 * @return String: converted text
589 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
592 $length = strlen( $text );
593 while ( $startPos < $length ) {
594 $pos = strpos( $text, '-{', $startPos );
596 if ( $pos === false ) {
597 // No more markup, append final segment
598 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
603 // Append initial segment
604 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
609 // Do recursive conversion
610 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
617 * Recursively convert text on the inside.
619 * @param $text String: text to be converted
620 * @param $variant String: the target variant code
621 * @param $startPos int
622 * @param $depth Integer: depth of recursion
624 * @return String: converted text
626 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
627 // Quick sanity check (no function calls)
628 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
629 throw new MWException( __METHOD__
. ': invalid input string' );
634 $warningDone = false;
635 $length = strlen( $text );
637 while ( $startPos < $length ) {
639 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
649 // Append initial segment
650 $inner .= substr( $text, $startPos, $pos - $startPos );
658 if ( $depth >= $this->mMaxDepth
) {
660 if ( !$warningDone ) {
661 $inner .= '<span class="error">' .
662 wfMsgForContent( 'language-converter-depth-warning',
670 // Recursively parse another rule
671 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
676 $rule = new ConverterRule( $inner, $this );
677 $rule->parse( $variant );
678 $this->applyManualConv( $rule );
679 return $rule->getDisplay();
681 throw new MWException( __METHOD__
. ': invalid regex match' );
686 if ( $startPos < $length ) {
687 $inner .= substr( $text, $startPos );
690 return '-{' . $this->autoConvert( $inner, $variant );
694 * If a language supports multiple variants, it is possible that
695 * non-existing link in one variant actually exists in another variant.
696 * This function tries to find it. See e.g. LanguageZh.php
698 * @param $link String: the name of the link
699 * @param $nt Mixed: the title object of the link
700 * @param $ignoreOtherCond Boolean: to disable other conditions when
701 * we need to transclude a template or update a category's link
702 * @return Null, the input parameters may be modified upon return
704 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
705 # If the article has already existed, there is no need to
706 # check it again, otherwise it may cause a fault.
707 if ( is_object( $nt ) && $nt->exists() ) {
711 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
713 $isredir = $wgRequest->getText( 'redirect', 'yes' );
714 $action = $wgRequest->getText( 'action' );
715 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
716 $disableLinkConversion = $wgDisableLangConversion
717 ||
$wgDisableTitleConversion;
718 $linkBatch = new LinkBatch();
722 if ( $disableLinkConversion ||
723 ( !$ignoreOtherCond &&
726 ||
$action == 'submit'
727 ||
$linkconvert == 'no'
728 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
732 if ( is_object( $nt ) ) {
733 $ns = $nt->getNamespace();
736 $variants = $this->autoConvertToAllVariants( $link );
737 if ( !$variants ) { // give up
743 foreach ( $variants as $v ) {
745 $varnt = Title
::newFromText( $v, $ns );
746 if ( !is_null( $varnt ) ) {
747 $linkBatch->addObj( $varnt );
753 // fetch all variants in single query
754 $linkBatch->execute();
756 foreach ( $titles as $varnt ) {
757 if ( $varnt->getArticleID() > 0 ) {
759 $link = $varnt->getText();
766 * Returns language specific hash options.
770 public function getExtraHashOptions() {
771 $variant = $this->getPreferredVariant();
772 return '!' . $variant;
776 * Load default conversion tables.
777 * This method must be implemented in derived class.
781 function loadDefaultTables() {
782 $name = get_class( $this );
783 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
787 * Load conversion tables either from the cache or the disk.
789 * @param $fromCache Boolean: load from memcached? Defaults to true.
791 function loadTables( $fromCache = true ) {
792 if ( $this->mTablesLoaded
) {
796 wfProfileIn( __METHOD__
);
797 $this->mTablesLoaded
= true;
798 $this->mTables
= false;
800 wfProfileIn( __METHOD__
. '-cache' );
801 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
802 wfProfileOut( __METHOD__
. '-cache' );
805 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
806 wfProfileIn( __METHOD__
. '-recache' );
807 // not in cache, or we need a fresh reload.
808 // We will first load the default tables
809 // then update them using things in MediaWiki:Conversiontable/*
810 $this->loadDefaultTables();
811 foreach ( $this->mVariants
as $var ) {
812 $cached = $this->parseCachedTable( $var );
813 $this->mTables
[$var]->mergeArray( $cached );
816 $this->postLoadTables();
817 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
819 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
820 wfProfileOut( __METHOD__
. '-recache' );
822 wfProfileOut( __METHOD__
);
826 * Hook for post processing after conversion tables are loaded.
828 function postLoadTables() { }
831 * Reload the conversion tables.
835 function reloadTables() {
836 if ( $this->mTables
) {
837 unset( $this->mTables
);
839 $this->mTablesLoaded
= false;
840 $this->loadTables( false );
844 * Parse the conversion table stored in the cache.
846 * The tables should be in blocks of the following form:
853 * To make the tables more manageable, subpages are allowed
854 * and will be parsed recursively if $recursive == true.
856 * @param $code String: language code
857 * @param $subpage String: subpage name
858 * @param $recursive Boolean: parse subpages recursively? Defaults to true.
862 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
863 static $parsed = array();
865 $key = 'Conversiontable/' . $code;
867 $key .= '/' . $subpage;
869 if ( array_key_exists( $key, $parsed ) ) {
873 if ( strpos( $code, '/' ) === false ) {
874 $txt = MessageCache
::singleton()->get( 'Conversiontable', true, $code );
875 if ( $txt === false ) {
876 # @todo FIXME: This method doesn't seem to be expecting
877 # this possible outcome...
878 $txt = '<Conversiontable>';
881 $title = Title
::makeTitleSafe(
883 "Conversiontable/$code"
885 if ( $title && $title->exists() ) {
886 $article = new Article( $title );
887 $txt = $article->getContents();
893 // get all subpage links of the form
894 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
895 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
897 $subs = StringUtils
::explode( '[[', $txt );
899 foreach ( $subs as $sub ) {
900 $link = explode( ']]', $sub, 2 );
901 if ( count( $link ) != 2 ) {
904 $b = explode( '|', $link[0], 2 );
905 $b = explode( '/', trim( $b[0] ), 3 );
906 if ( count( $b ) == 3 ) {
912 if ( $b[0] == $linkhead && $b[1] == $code ) {
913 $sublinks[] = $sublink;
917 // parse the mappings in this page
918 $blocks = StringUtils
::explode( '-{', $txt );
921 foreach ( $blocks as $block ) {
923 // Skip the part before the first -{
927 $mappings = explode( '}-', $block, 2 );
928 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
930 $table = StringUtils
::explode( ';', $stripped );
931 foreach ( $table as $t ) {
932 $m = explode( '=>', $t, 3 );
933 if ( count( $m ) != 2 ) {
936 // trim any trailling comments starting with '//'
937 $tt = explode( '//', $m[1], 2 );
938 $ret[trim( $m[0] )] = trim( $tt[0] );
941 $parsed[$key] = true;
943 // recursively parse the subpages
945 foreach ( $sublinks as $link ) {
946 $s = $this->parseCachedTable( $code, $link, $recursive );
947 $ret = array_merge( $ret, $s );
951 if ( $this->mUcfirst
) {
952 foreach ( $ret as $k => $v ) {
953 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
960 * Enclose a string with the "no conversion" tag. This is used by
961 * various functions in the Parser.
963 * @param $text String: text to be tagged for no conversion
964 * @param $noParse Boolean: unused
965 * @return String: the tagged text
967 public function markNoConversion( $text, $noParse = false ) {
968 # don't mark if already marked
969 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
973 $ret = "-{R|$text}-";
978 * Convert the sorting key for category links. This should make different
979 * keys that are variants of each other map to the same key.
985 function convertCategoryKey( $key ) {
990 * Hook to refresh the cache of conversion tables when
991 * MediaWiki:Conversiontable* is updated.
994 * @param $article Article object
995 * @param $user Object: User object for the current user
996 * @param $text String: article text (?)
997 * @param $summary String: edit summary of the edit
998 * @param $isMinor Boolean: was the edit marked as minor?
999 * @param $isWatch Boolean: did the user watch this page or not?
1000 * @param $section Unused
1001 * @param $flags Bitfield
1002 * @param $revision Object: new Revision object or null
1003 * @return Boolean: true
1005 function OnArticleSaveComplete( $article, $user, $text, $summary, $isMinor,
1006 $isWatch, $section, $flags, $revision ) {
1007 $titleobj = $article->getTitle();
1008 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1009 $title = $titleobj->getDBkey();
1010 $t = explode( '/', $title, 3 );
1012 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1013 if ( $this->validateVariant( $t[1] ) ) {
1014 $this->reloadTables();
1022 * Armour rendered math against conversion.
1023 * Escape special chars in parsed math text. (in most cases are img elements)
1025 * @param $text String: text to armour against conversion
1026 * @return String: armoured text where { and } have been converted to
1029 public function armourMath( $text ) {
1030 // convert '-{' and '}-' to '-{' and '}-' to prevent
1031 // any unwanted markup appearing in the math image tag.
1032 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
1037 * Get the cached separator pattern for ConverterRule::parseRules()
1039 function getVarSeparatorPattern() {
1040 if ( is_null( $this->mVarSeparatorPattern
) ) {
1041 // varsep_pattern for preg_split:
1042 // text should be splited by ";" only if a valid variant
1043 // name exist after the markup, for example:
1044 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1045 // <span style="font-size:120%;">yyy</span>;}-
1046 // we should split it as:
1048 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1049 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1053 foreach ( $this->mVariants
as $variant ) {
1054 // zh-hans:xxx;zh-hant:yyy
1055 $pat .= $variant . '\s*:|';
1056 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1057 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1060 $this->mVarSeparatorPattern
= $pat;
1062 return $this->mVarSeparatorPattern
;
1067 * Parser for rules of language conversion , parse rules in -{ }- tag.
1069 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1071 class ConverterRule
{
1072 var $mText; // original text in -{text}-
1073 var $mConverter; // LanguageConverter object
1074 var $mManualCodeError = '<strong class="error">code error!</strong>';
1075 var $mRuleDisplay = '';
1076 var $mRuleTitle = false;
1077 var $mRules = '';// string : the text of the rules
1078 var $mRulesAction = 'none';
1079 var $mFlags = array();
1080 var $mVariantFlags = array();
1081 var $mConvTable = array();
1082 var $mBidtable = array();// array of the translation in each variant
1083 var $mUnidtable = array();// array of the translation in each variant
1088 * @param $text String: the text between -{ and }-
1089 * @param $converter LanguageConverter object
1091 public function __construct( $text, $converter ) {
1092 $this->mText
= $text;
1093 $this->mConverter
= $converter;
1097 * Check if variants array in convert array.
1099 * @param $variants Array or string: variant language code
1100 * @return String: translated text
1102 public function getTextInBidtable( $variants ) {
1103 $variants = (array)$variants;
1107 foreach ( $variants as $variant ) {
1108 if ( isset( $this->mBidtable
[$variant] ) ) {
1109 return $this->mBidtable
[$variant];
1116 * Parse flags with syntax -{FLAG| ... }-
1119 function parseFlags() {
1120 $text = $this->mText
;
1122 $variantFlags = array();
1124 $sepPos = strpos( $text, '|' );
1125 if ( $sepPos !== false ) {
1126 $validFlags = $this->mConverter
->mFlags
;
1127 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1128 foreach ( $f as $ff ) {
1130 if ( isset( $validFlags[$ff] ) ) {
1131 $flags[$validFlags[$ff]] = true;
1134 $text = strval( substr( $text, $sepPos +
1 ) );
1139 } elseif ( isset( $flags['R'] ) ) {
1140 $flags = array( 'R' => true );// remove other flags
1141 } elseif ( isset( $flags['N'] ) ) {
1142 $flags = array( 'N' => true );// remove other flags
1143 } elseif ( isset( $flags['-'] ) ) {
1144 $flags = array( '-' => true );// remove other flags
1145 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1147 } elseif ( isset( $flags['H'] ) ) {
1148 // replace A flag, and remove other flags except T
1149 $temp = array( '+' => true, 'H' => true );
1150 if ( isset( $flags['T'] ) ) {
1153 if ( isset( $flags['D'] ) ) {
1158 if ( isset( $flags['A'] ) ) {
1162 if ( isset( $flags['D'] ) ) {
1163 unset( $flags['S'] );
1165 // try to find flags like "zh-hans", "zh-hant"
1166 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1167 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1168 if ( $variantFlags ) {
1169 $variantFlags = array_flip( $variantFlags );
1173 $this->mVariantFlags
= $variantFlags;
1174 $this->mRules
= $text;
1175 $this->mFlags
= $flags;
1179 * Generate conversion table.
1182 function parseRules() {
1183 $rules = $this->mRules
;
1184 $bidtable = array();
1185 $unidtable = array();
1186 $variants = $this->mConverter
->mVariants
;
1187 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1189 $choice = preg_split( $varsep_pattern, $rules );
1191 foreach ( $choice as $c ) {
1192 $v = explode( ':', $c, 2 );
1193 if ( count( $v ) != 2 ) {
1194 // syntax error, skip
1197 $to = trim( $v[1] );
1199 $u = explode( '=>', $v, 2 );
1200 // if $to is empty, strtr() could return a wrong result
1201 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1202 $bidtable[$v] = $to;
1203 } elseif ( count( $u ) == 2 ) {
1204 $from = trim( $u[0] );
1206 if ( array_key_exists( $v, $unidtable )
1207 && !is_array( $unidtable[$v] )
1209 && in_array( $v, $variants ) ) {
1210 $unidtable[$v] = array( $from => $to );
1211 } elseif ( $to && in_array( $v, $variants ) ) {
1212 $unidtable[$v][$from] = $to;
1215 // syntax error, pass
1216 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1217 $bidtable = array();
1218 $unidtable = array();
1222 $this->mBidtable
= $bidtable;
1223 $this->mUnidtable
= $unidtable;
1231 function getRulesDesc() {
1232 $codesep = $this->mConverter
->mDescCodeSep
;
1233 $varsep = $this->mConverter
->mDescVarSep
;
1235 foreach ( $this->mBidtable
as $k => $v ) {
1236 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1238 foreach ( $this->mUnidtable
as $k => $a ) {
1239 foreach ( $a as $from => $to ) {
1240 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1241 "$codesep$to$varsep";
1248 * Parse rules conversion.
1255 function getRuleConvertedStr( $variant ) {
1256 $bidtable = $this->mBidtable
;
1257 $unidtable = $this->mUnidtable
;
1259 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1260 return $this->mRules
;
1262 // display current variant in bidirectional array
1263 $disp = $this->getTextInBidtable( $variant );
1264 // or display current variant in fallbacks
1266 $disp = $this->getTextInBidtable(
1267 $this->mConverter
->getVariantFallbacks( $variant ) );
1269 // or display current variant in unidirectional array
1270 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1271 $disp = array_values( $unidtable[$variant] );
1274 // or display frist text under disable manual convert
1276 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1277 if ( count( $bidtable ) > 0 ) {
1278 $disp = array_values( $bidtable );
1281 $disp = array_values( $unidtable );
1282 $disp = array_values( $disp[0] );
1291 * Generate conversion table for all text.
1294 function generateConvTable() {
1295 // Special case optimisation
1296 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1297 $this->mConvTable
= array();
1301 $bidtable = $this->mBidtable
;
1302 $unidtable = $this->mUnidtable
;
1303 $manLevel = $this->mConverter
->mManualLevel
;
1306 foreach ( $this->mConverter
->mVariants
as $v ) {
1307 /* for bidirectional array
1308 fill in the missing variants, if any,
1310 if ( !isset( $bidtable[$v] ) ) {
1312 $this->mConverter
->getVariantFallbacks( $v );
1313 $vf = $this->getTextInBidtable( $variantFallbacks );
1315 $bidtable[$v] = $vf;
1319 if ( isset( $bidtable[$v] ) ) {
1320 foreach ( $vmarked as $vo ) {
1321 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1322 // or -{H|zh:WordZh;zh-tw:WordTw}-
1323 // or -{-|zh:WordZh;zh-tw:WordTw}-
1324 // to introduce a custom mapping between
1325 // words WordZh and WordTw in the whole text
1326 if ( $manLevel[$v] == 'bidirectional' ) {
1327 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1329 if ( $manLevel[$vo] == 'bidirectional' ) {
1330 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1335 /* for unidirectional array fill to convert tables */
1336 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1337 && isset( $unidtable[$v] ) )
1339 if ( isset( $this->mConvTable
[$v] ) ) {
1340 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1342 $this->mConvTable
[$v] = $unidtable[$v];
1349 * Parse rules and flags.
1350 * @param $variant String: variant language code
1352 public function parse( $variant = null ) {
1354 $variant = $this->mConverter
->getPreferredVariant();
1357 $this->parseFlags();
1358 $flags = $this->mFlags
;
1360 // convert to specified variant
1361 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1362 if ( $this->mVariantFlags
) {
1363 // check if current variant in flags
1364 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1365 // then convert <text to convert> to current language
1366 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1368 } else { // if current variant no in flags,
1369 // then we check its fallback variants.
1371 $this->mConverter
->getVariantFallbacks( $variant );
1372 foreach ( $variantFallbacks as $variantFallback ) {
1373 // if current variant's fallback exist in flags
1374 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1375 // then convert <text to convert> to fallback language
1377 $this->mConverter
->autoConvert( $this->mRules
,
1383 $this->mFlags
= $flags = array( 'R' => true );
1386 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1387 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1388 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1389 $this->parseRules();
1391 $rules = $this->mRules
;
1393 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1394 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1395 // fill all variants if text in -{A/H/-|text} without rules
1396 foreach ( $this->mConverter
->mVariants
as $v ) {
1397 $this->mBidtable
[$v] = $rules;
1399 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1400 $this->mFlags
= $flags = array( 'R' => true );
1404 $this->mRuleDisplay
= false;
1405 foreach ( $flags as $flag => $unused ) {
1408 // if we don't do content convert, still strip the -{}- tags
1409 $this->mRuleDisplay
= $rules;
1412 // process N flag: output current variant name
1413 $ruleVar = trim( $rules );
1414 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1415 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1417 $this->mRuleDisplay
= '';
1421 // process D flag: output rules description
1422 $this->mRuleDisplay
= $this->getRulesDesc();
1425 // process H,- flag or T only: output nothing
1426 $this->mRuleDisplay
= '';
1429 $this->mRulesAction
= 'remove';
1430 $this->mRuleDisplay
= '';
1433 $this->mRulesAction
= 'add';
1434 $this->mRuleDisplay
= '';
1437 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1440 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1441 $this->mRuleDisplay
= '';
1444 // ignore unknown flags (but see error case below)
1447 if ( $this->mRuleDisplay
=== false ) {
1448 $this->mRuleDisplay
= $this->mManualCodeError
;
1451 $this->generateConvTable();
1455 * @todo FIXME: code this function :)
1457 public function hasRules() {
1462 * Get display text on markup -{...}-
1465 public function getDisplay() {
1466 return $this->mRuleDisplay
;
1470 * Get converted title.
1473 public function getTitle() {
1474 return $this->mRuleTitle
;
1478 * Return how deal with conversion rules.
1481 public function getRulesAction() {
1482 return $this->mRulesAction
;
1486 * Get conversion table. (bidirectional and unidirectional
1490 public function getConvTable() {
1491 return $this->mConvTable
;
1495 * Get conversion rules string.
1498 public function getRules() {
1499 return $this->mRules
;
1503 * Get conversion flags.
1506 public function getFlags() {
1507 return $this->mFlags
;