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 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 if( $this->guessVariant( $text, $toVariant ) ) {
329 /* we convert everything except:
330 1. HTML markups (anything between < and >)
332 3. placeholders created by the parser
335 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
336 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
341 // this one is needed when the text is inside an HTML markup
342 $htmlfix = '|<[^>]+$|^[^<>]*>';
344 // disable convert to variants between <code></code> tags
345 $codefix = '<code>.+?<\/code>|';
346 // disable convertsion of <script type="text/javascript"> ... </script>
347 $scriptfix = '<script.*?>.*?<\/script>|';
348 // disable conversion of <pre xxxx> ... </pre>
349 $prefix = '<pre.*?>.*?<\/pre>|';
351 $reg = '/' . $codefix . $scriptfix . $prefix .
352 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
357 // Guard against delimiter nulls in the input
358 $text = str_replace( "\000", '', $text );
360 $markupMatches = null;
361 $elementMatches = null;
362 while ( $startPos < strlen( $text ) ) {
363 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
364 $elementPos = $markupMatches[0][1];
365 $element = $markupMatches[0][0];
367 $elementPos = strlen( $text );
371 // Queue the part before the markup for translation in a batch
372 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
374 // Advance to the next position
375 $startPos = $elementPos +
strlen( $element );
377 // Translate any alt or title attributes inside the matched element
378 if ( $element !== '' && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element,
381 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
383 foreach ( array( 'title', 'alt' ) as $attrName ) {
384 if ( !isset( $attrs[$attrName] ) ) {
387 $attr = $attrs[$attrName];
388 // Don't convert URLs
389 if ( !strpos( $attr, '://' ) ) {
390 $attr = $this->translate( $attr, $toVariant );
393 // Remove HTML tags to avoid disrupting the layout
394 $attr = preg_replace( '/<[^>]+>/', '', $attr );
395 if ( $attr !== $attrs[$attrName] ) {
396 $attrs[$attrName] = $attr;
401 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
405 $literalBlob .= $element . "\000";
408 // Do the main translation batch
409 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
411 // Put the output back together
412 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
413 $literalIter = StringUtils
::explode( "\000", $literalBlob );
415 while ( $translatedIter->valid() && $literalIter->valid() ) {
416 $output .= $translatedIter->current();
417 $output .= $literalIter->current();
418 $translatedIter->next();
419 $literalIter->next();
422 wfProfileOut( __METHOD__
);
427 * Translate a string to a variant.
428 * Doesn't parse rules or do any of that other stuff, for that use
429 * convert() or convertTo().
431 * @param $text String: text to convert
432 * @param $variant String: variant language code
433 * @return String: translated text
435 public function translate( $text, $variant ) {
436 wfProfileIn( __METHOD__
);
437 // If $text is empty or only includes spaces, do nothing
438 // Otherwise translate it
439 if ( trim( $text ) ) {
441 $text = $this->mTables
[$variant]->replace( $text );
443 wfProfileOut( __METHOD__
);
448 * Call translate() to convert text to all valid variants.
450 * @param $text String: the text to be converted
451 * @return Array: variant => converted text
453 public function autoConvertToAllVariants( $text ) {
454 wfProfileIn( __METHOD__
);
458 foreach ( $this->mVariants
as $variant ) {
459 $ret[$variant] = $this->translate( $text, $variant );
462 wfProfileOut( __METHOD__
);
467 * Convert link text to all valid variants.
468 * In the first, this function only convert text outside the
469 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
470 * titles, the text will get all converted always.
471 * So I removed this feature and deprecated the function.
473 * @param $text String: the text to be converted
474 * @return Array: variant => converted text
475 * @deprecated Use autoConvertToAllVariants() instead
477 public function convertLinkToAllVariants( $text ) {
478 return $this->autoConvertToAllVariants( $text );
482 * Apply manual conversion rules.
484 * @param $convRule Object: Object of ConverterRule
486 protected function applyManualConv( $convRule ) {
487 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
489 // Bug 24072: $mConvRuleTitle was overwritten by other manual
490 // rule(s) not for title, this breaks the title conversion.
491 $newConvRuleTitle = $convRule->getTitle();
492 if ( $newConvRuleTitle ) {
493 // So I add an empty check for getTitle()
494 $this->mConvRuleTitle
= $newConvRuleTitle;
497 // merge/remove manual conversion rules to/from global table
498 $convTable = $convRule->getConvTable();
499 $action = $convRule->getRulesAction();
500 foreach ( $convTable as $variant => $pair ) {
501 if ( !$this->validateVariant( $variant ) ) {
505 if ( $action == 'add' ) {
506 foreach ( $pair as $from => $to ) {
507 // to ensure that $from and $to not be left blank
508 // so $this->translate() could always return a string
509 if ( $from ||
$to ) {
510 // more efficient than array_merge(), about 2.5 times.
511 $this->mTables
[$variant]->setPair( $from, $to );
514 } elseif ( $action == 'remove' ) {
515 $this->mTables
[$variant]->removeArray( $pair );
521 * Auto convert a Title object to a readable string in the
524 * @param $title Object: a object of Title
525 * @return String: converted title text
527 public function convertTitle( $title ) {
528 $variant = $this->getPreferredVariant();
529 $index = $title->getNamespace();
530 if ( $index === NS_MAIN
) {
533 // first let's check if a message has given us a converted name
534 $nsConvKey = 'conversion-ns' . $index;
535 if ( !wfEmptyMsg( $nsConvKey ) ) {
536 $text = wfMsgForContentNoTrans( $nsConvKey );
538 // the message does not exist, try retrieve it from the current
539 // variant's namespace names.
540 $langObj = $this->mLangObj
->factory( $variant );
541 $text = $langObj->getFormattedNsText( $index );
545 $text .= $title->getText();
546 $text = $this->translate( $text, $variant );
551 * Convert text to different variants of a language. The automatic
552 * conversion is done in autoConvert(). Here we parse the text
553 * marked with -{}-, which specifies special conversions of the
554 * text that can not be accomplished in autoConvert().
556 * Syntax of the markup:
557 * -{code1:text1;code2:text2;...}- or
558 * -{flags|code1:text1;code2:text2;...}- or
559 * -{text}- in which case no conversion should take place for text
561 * @param $text String: text to be converted
562 * @return String: converted text
564 public function convert( $text ) {
565 $variant = $this->getPreferredVariant();
566 return $this->convertTo( $text, $variant );
570 * Same as convert() except a extra parameter to custom variant.
572 * @param $text String: text to be converted
573 * @param $variant String: the target variant code
574 * @return String: converted text
576 public function convertTo( $text, $variant ) {
577 global $wgDisableLangConversion;
578 if ( $wgDisableLangConversion ||
$this->guessVariant( $text, $variant ) ) {
581 return $this->recursiveConvertTopLevel( $text, $variant );
585 * Recursively convert text on the outside. Allow to use nested
586 * markups to custom rules.
588 * @param $text String: text to be converted
589 * @param $variant String: the target variant code
590 * @param $depth Integer: depth of recursion
591 * @return String: converted text
593 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
596 $length = strlen( $text );
597 while ( $startPos < $length ) {
598 $pos = strpos( $text, '-{', $startPos );
600 if ( $pos === false ) {
601 // No more markup, append final segment
602 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
607 // Append initial segment
608 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
613 // Do recursive conversion
614 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
621 * Recursively convert text on the inside.
623 * @param $text String: text to be converted
624 * @param $variant String: the target variant code
625 * @param $depth Integer: depth of recursion
626 * @return String: converted text
628 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
629 // Quick sanity check (no function calls)
630 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
631 throw new MWException( __METHOD__
. ': invalid input string' );
636 $warningDone = false;
637 $length = strlen( $text );
639 while ( $startPos < $length ) {
641 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
651 // Append initial segment
652 $inner .= substr( $text, $startPos, $pos - $startPos );
660 if ( $depth >= $this->mMaxDepth
) {
662 if ( !$warningDone ) {
663 $inner .= '<span class="error">' .
664 wfMsgForContent( 'language-converter-depth-warning',
672 // Recursively parse another rule
673 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
678 $rule = new ConverterRule( $inner, $this );
679 $rule->parse( $variant );
680 $this->applyManualConv( $rule );
681 return $rule->getDisplay();
683 throw new MWException( __METHOD__
. ': invalid regex match' );
688 if ( $startPos < $length ) {
689 $inner .= substr( $text, $startPos );
692 return '-{' . $this->autoConvert( $inner, $variant );
696 * If a language supports multiple variants, it is possible that
697 * non-existing link in one variant actually exists in another variant.
698 * This function tries to find it. See e.g. LanguageZh.php
700 * @param $link String: the name of the link
701 * @param $nt Mixed: the title object of the link
702 * @param $ignoreOtherCond Boolean: to disable other conditions when
703 * we need to transclude a template or update a category's link
704 * @return Null, the input parameters may be modified upon return
706 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
707 # If the article has already existed, there is no need to
708 # check it again, otherwise it may cause a fault.
709 if ( is_object( $nt ) && $nt->exists() ) {
713 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
715 $isredir = $wgRequest->getText( 'redirect', 'yes' );
716 $action = $wgRequest->getText( 'action' );
717 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
718 $disableLinkConversion = $wgDisableLangConversion
719 ||
$wgDisableTitleConversion;
720 $linkBatch = new LinkBatch();
724 if ( $disableLinkConversion ||
725 ( !$ignoreOtherCond &&
728 ||
$action == 'submit'
729 ||
$linkconvert == 'no'
730 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
734 if ( is_object( $nt ) ) {
735 $ns = $nt->getNamespace();
738 $variants = $this->autoConvertToAllVariants( $link );
739 if ( !$variants ) { // give up
745 foreach ( $variants as $v ) {
747 $varnt = Title
::newFromText( $v, $ns );
748 if ( !is_null( $varnt ) ) {
749 $linkBatch->addObj( $varnt );
755 // fetch all variants in single query
756 $linkBatch->execute();
758 foreach ( $titles as $varnt ) {
759 if ( $varnt->getArticleID() > 0 ) {
761 $link = $varnt->getText();
768 * Returns language specific hash options.
770 public function getExtraHashOptions() {
771 $variant = $this->getPreferredVariant();
772 return '!' . $variant;
776 * Guess if a text is written in a variant. This should be implemented in subclasses.
778 * @param string $text the text to be checked
779 * @param string $variant language code of the variant to be checked for
780 * @return bool true if $text appears to be written in $variant, false if not
782 * @author Nikola Smolenski <smolensk@eunet.rs>
785 public function guessVariant($text, $variant) {
790 * Load default conversion tables.
791 * This method must be implemented in derived class.
795 function loadDefaultTables() {
796 $name = get_class( $this );
797 wfDie( "Must implement loadDefaultTables() method in class $name" );
801 * Load conversion tables either from the cache or the disk.
803 * @param $fromCache Boolean: load from memcached? Defaults to true.
805 function loadTables( $fromCache = true ) {
806 if ( $this->mTablesLoaded
) {
810 wfProfileIn( __METHOD__
);
811 $this->mTablesLoaded
= true;
812 $this->mTables
= false;
814 wfProfileIn( __METHOD__
. '-cache' );
815 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
816 wfProfileOut( __METHOD__
. '-cache' );
819 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
820 wfProfileIn( __METHOD__
. '-recache' );
821 // not in cache, or we need a fresh reload.
822 // We will first load the default tables
823 // then update them using things in MediaWiki:Conversiontable/*
824 $this->loadDefaultTables();
825 foreach ( $this->mVariants
as $var ) {
826 $cached = $this->parseCachedTable( $var );
827 $this->mTables
[$var]->mergeArray( $cached );
830 $this->postLoadTables();
831 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
833 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
834 wfProfileOut( __METHOD__
. '-recache' );
836 wfProfileOut( __METHOD__
);
840 * Hook for post processing after conversion tables are loaded.
842 function postLoadTables() { }
845 * Reload the conversion tables.
849 function reloadTables() {
850 if ( $this->mTables
) {
851 unset( $this->mTables
);
853 $this->mTablesLoaded
= false;
854 $this->loadTables( false );
858 * Parse the conversion table stored in the cache.
860 * The tables should be in blocks of the following form:
867 * To make the tables more manageable, subpages are allowed
868 * and will be parsed recursively if $recursive == true.
870 * @param $code String: language code
871 * @param $subpage String: subpage name
872 * @param $recursive Boolean: parse subpages recursively? Defaults to true.
874 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
875 static $parsed = array();
877 $key = 'Conversiontable/' . $code;
879 $key .= '/' . $subpage;
881 if ( array_key_exists( $key, $parsed ) ) {
885 if ( strpos( $code, '/' ) === false ) {
886 $txt = MessageCache
::singleton()->get( 'Conversiontable', true, $code );
887 if ( $txt === false ) {
888 # FIXME: this method doesn't seem to be expecting
889 # this possible outcome...
890 $txt = '<Conversiontable>';
893 $title = Title
::makeTitleSafe(
895 "Conversiontable/$code"
897 if ( $title && $title->exists() ) {
898 $article = new Article( $title );
899 $txt = $article->getContents();
905 // get all subpage links of the form
906 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
907 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
909 $subs = StringUtils
::explode( '[[', $txt );
911 foreach ( $subs as $sub ) {
912 $link = explode( ']]', $sub, 2 );
913 if ( count( $link ) != 2 ) {
916 $b = explode( '|', $link[0], 2 );
917 $b = explode( '/', trim( $b[0] ), 3 );
918 if ( count( $b ) == 3 ) {
924 if ( $b[0] == $linkhead && $b[1] == $code ) {
925 $sublinks[] = $sublink;
929 // parse the mappings in this page
930 $blocks = StringUtils
::explode( '-{', $txt );
933 foreach ( $blocks as $block ) {
935 // Skip the part before the first -{
939 $mappings = explode( '}-', $block, 2 );
940 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
942 $table = StringUtils
::explode( ';', $stripped );
943 foreach ( $table as $t ) {
944 $m = explode( '=>', $t, 3 );
945 if ( count( $m ) != 2 ) {
948 // trim any trailling comments starting with '//'
949 $tt = explode( '//', $m[1], 2 );
950 $ret[trim( $m[0] )] = trim( $tt[0] );
953 $parsed[$key] = true;
955 // recursively parse the subpages
957 foreach ( $sublinks as $link ) {
958 $s = $this->parseCachedTable( $code, $link, $recursive );
959 $ret = array_merge( $ret, $s );
963 if ( $this->mUcfirst
) {
964 foreach ( $ret as $k => $v ) {
965 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
972 * Enclose a string with the "no conversion" tag. This is used by
973 * various functions in the Parser.
975 * @param $text String: text to be tagged for no conversion
976 * @param $noParse Boolean: unused
977 * @return String: the tagged text
979 public function markNoConversion( $text, $noParse = false ) {
980 # don't mark if already marked
981 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
985 $ret = "-{R|$text}-";
990 * Convert the sorting key for category links. This should make different
991 * keys that are variants of each other map to the same key.
993 function convertCategoryKey( $key ) {
998 * Hook to refresh the cache of conversion tables when
999 * MediaWiki:Conversiontable* is updated.
1002 * @param $article Object: Article object
1003 * @param $user Object: User object for the current user
1004 * @param $text String: article text (?)
1005 * @param $summary String: edit summary of the edit
1006 * @param $isMinor Boolean: was the edit marked as minor?
1007 * @param $isWatch Boolean: did the user watch this page or not?
1008 * @param $section Unused
1009 * @param $flags Bitfield
1010 * @param $revision Object: new Revision object or null
1011 * @return Boolean: true
1013 function OnArticleSaveComplete( $article, $user, $text, $summary, $isMinor,
1014 $isWatch, $section, $flags, $revision ) {
1015 $titleobj = $article->getTitle();
1016 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1017 $title = $titleobj->getDBkey();
1018 $t = explode( '/', $title, 3 );
1020 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1021 if ( $this->validateVariant( $t[1] ) ) {
1022 $this->reloadTables();
1030 * Armour rendered math against conversion.
1031 * Escape special chars in parsed math text. (in most cases are img elements)
1033 * @param $text String: text to armour against conversion
1034 * @return String: armoured text where { and } have been converted to
1037 public function armourMath( $text ) {
1038 // convert '-{' and '}-' to '-{' and '}-' to prevent
1039 // any unwanted markup appearing in the math image tag.
1040 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
1045 * Get the cached separator pattern for ConverterRule::parseRules()
1047 function getVarSeparatorPattern() {
1048 if ( is_null( $this->mVarSeparatorPattern
) ) {
1049 // varsep_pattern for preg_split:
1050 // text should be splited by ";" only if a valid variant
1051 // name exist after the markup, for example:
1052 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1053 // <span style="font-size:120%;">yyy</span>;}-
1054 // we should split it as:
1056 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1057 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1061 foreach ( $this->mVariants
as $variant ) {
1062 // zh-hans:xxx;zh-hant:yyy
1063 $pat .= $variant . '\s*:|';
1064 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1065 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1068 $this->mVarSeparatorPattern
= $pat;
1070 return $this->mVarSeparatorPattern
;
1075 * Parser for rules of language conversion , parse rules in -{ }- tag.
1077 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1079 class ConverterRule
{
1080 var $mText; // original text in -{text}-
1081 var $mConverter; // LanguageConverter object
1082 var $mManualCodeError = '<strong class="error">code error!</strong>';
1083 var $mRuleDisplay = '';
1084 var $mRuleTitle = false;
1085 var $mRules = '';// string : the text of the rules
1086 var $mRulesAction = 'none';
1087 var $mFlags = array();
1088 var $mVariantFlags = array();
1089 var $mConvTable = array();
1090 var $mBidtable = array();// array of the translation in each variant
1091 var $mUnidtable = array();// array of the translation in each variant
1096 * @param $text String: the text between -{ and }-
1097 * @param $converter LanguageConverter object
1099 public function __construct( $text, $converter ) {
1100 $this->mText
= $text;
1101 $this->mConverter
= $converter;
1105 * Check if variants array in convert array.
1107 * @param $variants Array or string: variant language code
1108 * @return String: translated text
1110 public function getTextInBidtable( $variants ) {
1111 $variants = (array)$variants;
1115 foreach ( $variants as $variant ) {
1116 if ( isset( $this->mBidtable
[$variant] ) ) {
1117 return $this->mBidtable
[$variant];
1124 * Parse flags with syntax -{FLAG| ... }-
1127 function parseFlags() {
1128 $text = $this->mText
;
1130 $variantFlags = array();
1132 $sepPos = strpos( $text, '|' );
1133 if ( $sepPos !== false ) {
1134 $validFlags = $this->mConverter
->mFlags
;
1135 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1136 foreach ( $f as $ff ) {
1138 if ( isset( $validFlags[$ff] ) ) {
1139 $flags[$validFlags[$ff]] = true;
1142 $text = strval( substr( $text, $sepPos +
1 ) );
1147 } elseif ( isset( $flags['R'] ) ) {
1148 $flags = array( 'R' => true );// remove other flags
1149 } elseif ( isset( $flags['N'] ) ) {
1150 $flags = array( 'N' => true );// remove other flags
1151 } elseif ( isset( $flags['-'] ) ) {
1152 $flags = array( '-' => true );// remove other flags
1153 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1155 } elseif ( isset( $flags['H'] ) ) {
1156 // replace A flag, and remove other flags except T
1157 $temp = array( '+' => true, 'H' => true );
1158 if ( isset( $flags['T'] ) ) {
1161 if ( isset( $flags['D'] ) ) {
1166 if ( isset( $flags['A'] ) ) {
1170 if ( isset( $flags['D'] ) ) {
1171 unset( $flags['S'] );
1173 // try to find flags like "zh-hans", "zh-hant"
1174 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1175 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1176 if ( $variantFlags ) {
1177 $variantFlags = array_flip( $variantFlags );
1181 $this->mVariantFlags
= $variantFlags;
1182 $this->mRules
= $text;
1183 $this->mFlags
= $flags;
1187 * Generate conversion table.
1190 function parseRules() {
1191 $rules = $this->mRules
;
1192 $bidtable = array();
1193 $unidtable = array();
1194 $variants = $this->mConverter
->mVariants
;
1195 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1197 $choice = preg_split( $varsep_pattern, $rules );
1199 foreach ( $choice as $c ) {
1200 $v = explode( ':', $c, 2 );
1201 if ( count( $v ) != 2 ) {
1202 // syntax error, skip
1205 $to = trim( $v[1] );
1207 $u = explode( '=>', $v, 2 );
1208 // if $to is empty, strtr() could return a wrong result
1209 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1210 $bidtable[$v] = $to;
1211 } elseif ( count( $u ) == 2 ) {
1212 $from = trim( $u[0] );
1214 if ( array_key_exists( $v, $unidtable )
1215 && !is_array( $unidtable[$v] )
1217 && in_array( $v, $variants ) ) {
1218 $unidtable[$v] = array( $from => $to );
1219 } elseif ( $to && in_array( $v, $variants ) ) {
1220 $unidtable[$v][$from] = $to;
1223 // syntax error, pass
1224 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1225 $bidtable = array();
1226 $unidtable = array();
1230 $this->mBidtable
= $bidtable;
1231 $this->mUnidtable
= $unidtable;
1237 function getRulesDesc() {
1238 $codesep = $this->mConverter
->mDescCodeSep
;
1239 $varsep = $this->mConverter
->mDescVarSep
;
1241 foreach ( $this->mBidtable
as $k => $v ) {
1242 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1244 foreach ( $this->mUnidtable
as $k => $a ) {
1245 foreach ( $a as $from => $to ) {
1246 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1247 "$codesep$to$varsep";
1254 * Parse rules conversion.
1257 function getRuleConvertedStr( $variant ) {
1258 $bidtable = $this->mBidtable
;
1259 $unidtable = $this->mUnidtable
;
1261 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1262 return $this->mRules
;
1264 // display current variant in bidirectional array
1265 $disp = $this->getTextInBidtable( $variant );
1266 // or display current variant in fallbacks
1268 $disp = $this->getTextInBidtable(
1269 $this->mConverter
->getVariantFallbacks( $variant ) );
1271 // or display current variant in unidirectional array
1272 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1273 $disp = array_values( $unidtable[$variant] );
1276 // or display frist text under disable manual convert
1278 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1279 if ( count( $bidtable ) > 0 ) {
1280 $disp = array_values( $bidtable );
1283 $disp = array_values( $unidtable );
1284 $disp = array_values( $disp[0] );
1293 * Generate conversion table for all text.
1296 function generateConvTable() {
1297 // Special case optimisation
1298 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1299 $this->mConvTable
= array();
1303 $bidtable = $this->mBidtable
;
1304 $unidtable = $this->mUnidtable
;
1305 $manLevel = $this->mConverter
->mManualLevel
;
1308 foreach ( $this->mConverter
->mVariants
as $v ) {
1309 /* for bidirectional array
1310 fill in the missing variants, if any,
1312 if ( !isset( $bidtable[$v] ) ) {
1314 $this->mConverter
->getVariantFallbacks( $v );
1315 $vf = $this->getTextInBidtable( $variantFallbacks );
1317 $bidtable[$v] = $vf;
1321 if ( isset( $bidtable[$v] ) ) {
1322 foreach ( $vmarked as $vo ) {
1323 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1324 // or -{H|zh:WordZh;zh-tw:WordTw}-
1325 // or -{-|zh:WordZh;zh-tw:WordTw}-
1326 // to introduce a custom mapping between
1327 // words WordZh and WordTw in the whole text
1328 if ( $manLevel[$v] == 'bidirectional' ) {
1329 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1331 if ( $manLevel[$vo] == 'bidirectional' ) {
1332 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1337 /* for unidirectional array fill to convert tables */
1338 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1339 && isset( $unidtable[$v] ) )
1341 if ( isset( $this->mConvTable
[$v] ) ) {
1342 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1344 $this->mConvTable
[$v] = $unidtable[$v];
1351 * Parse rules and flags.
1352 * @param $variant String: variant language code
1354 public function parse( $variant = null ) {
1356 $variant = $this->mConverter
->getPreferredVariant();
1359 $this->parseFlags();
1360 $flags = $this->mFlags
;
1362 // convert to specified variant
1363 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1364 if ( $this->mVariantFlags
) {
1365 // check if current variant in flags
1366 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1367 // then convert <text to convert> to current language
1368 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1370 } else { // if current variant no in flags,
1371 // then we check its fallback variants.
1373 $this->mConverter
->getVariantFallbacks( $variant );
1374 foreach ( $variantFallbacks as $variantFallback ) {
1375 // if current variant's fallback exist in flags
1376 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1377 // then convert <text to convert> to fallback language
1379 $this->mConverter
->autoConvert( $this->mRules
,
1385 $this->mFlags
= $flags = array( 'R' => true );
1388 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1389 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1390 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1391 $this->parseRules();
1393 $rules = $this->mRules
;
1395 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1396 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1397 // fill all variants if text in -{A/H/-|text} without rules
1398 foreach ( $this->mConverter
->mVariants
as $v ) {
1399 $this->mBidtable
[$v] = $rules;
1401 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1402 $this->mFlags
= $flags = array( 'R' => true );
1406 $this->mRuleDisplay
= false;
1407 foreach ( $flags as $flag => $unused ) {
1410 // if we don't do content convert, still strip the -{}- tags
1411 $this->mRuleDisplay
= $rules;
1414 // process N flag: output current variant name
1415 $ruleVar = trim( $rules );
1416 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1417 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1419 $this->mRuleDisplay
= '';
1423 // process D flag: output rules description
1424 $this->mRuleDisplay
= $this->getRulesDesc();
1427 // process H,- flag or T only: output nothing
1428 $this->mRuleDisplay
= '';
1431 $this->mRulesAction
= 'remove';
1432 $this->mRuleDisplay
= '';
1435 $this->mRulesAction
= 'add';
1436 $this->mRuleDisplay
= '';
1439 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1442 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1443 $this->mRuleDisplay
= '';
1446 // ignore unknown flags (but see error case below)
1449 if ( $this->mRuleDisplay
=== false ) {
1450 $this->mRuleDisplay
= $this->mManualCodeError
;
1453 $this->generateConvTable();
1457 * @todo FIXME: code this function :)
1459 public function hasRules() {
1464 * Get display text on markup -{...}-
1466 public function getDisplay() {
1467 return $this->mRuleDisplay
;
1471 * Get converted title.
1473 public function getTitle() {
1474 return $this->mRuleTitle
;
1478 * Return how deal with conversion rules.
1480 public function getRulesAction() {
1481 return $this->mRulesAction
;
1485 * Get conversion table. (bidirectional and unidirectional
1488 public function getConvTable() {
1489 return $this->mConvTable
;
1493 * Get conversion rules string.
1495 public function getRules() {
1496 return $this->mRules
;
1500 * Get conversion flags.
1502 public function getFlags() {
1503 return $this->mFlags
;