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|array: 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
161 if ( $this->validateVariant( $req ) ) {
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 if( $this->guessVariant( $text, $toVariant ) ) {
326 wfProfileOut( __METHOD__
);
330 /* we convert everything except:
331 1. HTML markups (anything between < and >)
333 3. placeholders created by the parser
336 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
337 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
342 // this one is needed when the text is inside an HTML markup
343 $htmlfix = '|<[^>]+$|^[^<>]*>';
345 // disable convert to variants between <code></code> tags
346 $codefix = '<code>.+?<\/code>|';
347 // disable convertsion of <script type="text/javascript"> ... </script>
348 $scriptfix = '<script.*?>.*?<\/script>|';
349 // disable conversion of <pre xxxx> ... </pre>
350 $prefix = '<pre.*?>.*?<\/pre>|';
352 $reg = '/' . $codefix . $scriptfix . $prefix .
353 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
358 // Guard against delimiter nulls in the input
359 $text = str_replace( "\000", '', $text );
361 $markupMatches = null;
362 $elementMatches = null;
363 while ( $startPos < strlen( $text ) ) {
364 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
365 $elementPos = $markupMatches[0][1];
366 $element = $markupMatches[0][0];
368 $elementPos = strlen( $text );
372 // Queue the part before the markup for translation in a batch
373 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
375 // Advance to the next position
376 $startPos = $elementPos +
strlen( $element );
378 // Translate any alt or title attributes inside the matched element
379 if ( $element !== '' && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element,
382 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
384 foreach ( array( 'title', 'alt' ) as $attrName ) {
385 if ( !isset( $attrs[$attrName] ) ) {
388 $attr = $attrs[$attrName];
389 // Don't convert URLs
390 if ( !strpos( $attr, '://' ) ) {
391 $attr = $this->translate( $attr, $toVariant );
394 // Remove HTML tags to avoid disrupting the layout
395 $attr = preg_replace( '/<[^>]+>/', '', $attr );
396 if ( $attr !== $attrs[$attrName] ) {
397 $attrs[$attrName] = $attr;
402 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
406 $literalBlob .= $element . "\000";
409 // Do the main translation batch
410 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
412 // Put the output back together
413 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
414 $literalIter = StringUtils
::explode( "\000", $literalBlob );
416 while ( $translatedIter->valid() && $literalIter->valid() ) {
417 $output .= $translatedIter->current();
418 $output .= $literalIter->current();
419 $translatedIter->next();
420 $literalIter->next();
423 wfProfileOut( __METHOD__
);
428 * Translate a string to a variant.
429 * Doesn't parse rules or do any of that other stuff, for that use
430 * convert() or convertTo().
432 * @param $text String: text to convert
433 * @param $variant String: variant language code
434 * @return String: translated text
436 public function translate( $text, $variant ) {
437 wfProfileIn( __METHOD__
);
438 // If $text is empty or only includes spaces, do nothing
439 // Otherwise translate it
440 if ( trim( $text ) ) {
442 $text = $this->mTables
[$variant]->replace( $text );
444 wfProfileOut( __METHOD__
);
449 * Call translate() to convert text to all valid variants.
451 * @param $text String: the text to be converted
452 * @return Array: variant => converted text
454 public function autoConvertToAllVariants( $text ) {
455 wfProfileIn( __METHOD__
);
459 foreach ( $this->mVariants
as $variant ) {
460 $ret[$variant] = $this->translate( $text, $variant );
463 wfProfileOut( __METHOD__
);
468 * Convert link text to all valid variants.
469 * In the first, this function only convert text outside the
470 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
471 * titles, the text will get all converted always.
472 * So I removed this feature and deprecated the function.
474 * @param $text String: the text to be converted
475 * @return Array: variant => converted text
476 * @deprecated since 1.17 Use autoConvertToAllVariants() instead
478 public function convertLinkToAllVariants( $text ) {
479 return $this->autoConvertToAllVariants( $text );
483 * Apply manual conversion rules.
485 * @param $convRule ConverterRule Object of ConverterRule
487 protected function applyManualConv( $convRule ) {
488 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
490 // Bug 24072: $mConvRuleTitle was overwritten by other manual
491 // rule(s) not for title, this breaks the title conversion.
492 $newConvRuleTitle = $convRule->getTitle();
493 if ( $newConvRuleTitle ) {
494 // So I add an empty check for getTitle()
495 $this->mConvRuleTitle
= $newConvRuleTitle;
498 // merge/remove manual conversion rules to/from global table
499 $convTable = $convRule->getConvTable();
500 $action = $convRule->getRulesAction();
501 foreach ( $convTable as $variant => $pair ) {
502 if ( !$this->validateVariant( $variant ) ) {
506 if ( $action == 'add' ) {
507 foreach ( $pair as $from => $to ) {
508 // to ensure that $from and $to not be left blank
509 // so $this->translate() could always return a string
510 if ( $from ||
$to ) {
511 // more efficient than array_merge(), about 2.5 times.
512 $this->mTables
[$variant]->setPair( $from, $to );
515 } elseif ( $action == 'remove' ) {
516 $this->mTables
[$variant]->removeArray( $pair );
522 * Auto convert a Title object to a readable string in the
525 * @param $title Title a object of Title
526 * @return String: converted title text
528 public function convertTitle( $title ) {
529 $variant = $this->getPreferredVariant();
530 $index = $title->getNamespace();
531 if ( $index === NS_MAIN
) {
534 // first let's check if a message has given us a converted name
535 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
536 if ( $nsConvMsg->exists() ) {
537 $text = $nsConvMsg->plain();
539 // the message does not exist, try retrieve it from the current
540 // variant's namespace names.
541 $langObj = $this->mLangObj
->factory( $variant );
542 $text = $langObj->getFormattedNsText( $index );
546 $text .= $title->getText();
547 $text = $this->translate( $text, $variant );
552 * Convert text to different variants of a language. The automatic
553 * conversion is done in autoConvert(). Here we parse the text
554 * marked with -{}-, which specifies special conversions of the
555 * text that can not be accomplished in autoConvert().
557 * Syntax of the markup:
558 * -{code1:text1;code2:text2;...}- or
559 * -{flags|code1:text1;code2:text2;...}- or
560 * -{text}- in which case no conversion should take place for text
562 * @param $text String: text to be converted
563 * @return String: converted text
565 public function convert( $text ) {
566 $variant = $this->getPreferredVariant();
567 return $this->convertTo( $text, $variant );
571 * Same as convert() except a extra parameter to custom variant.
573 * @param $text String: text to be converted
574 * @param $variant String: the target variant code
575 * @return String: converted text
577 public function convertTo( $text, $variant ) {
578 global $wgDisableLangConversion;
579 if ( $wgDisableLangConversion ||
$this->guessVariant( $text, $variant ) ) {
582 return $this->recursiveConvertTopLevel( $text, $variant );
586 * Recursively convert text on the outside. Allow to use nested
587 * markups to custom rules.
589 * @param $text String: text to be converted
590 * @param $variant String: the target variant code
591 * @param $depth Integer: depth of recursion
592 * @return String: converted text
594 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
597 $length = strlen( $text );
598 while ( $startPos < $length ) {
599 $pos = strpos( $text, '-{', $startPos );
601 if ( $pos === false ) {
602 // No more markup, append final segment
603 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
608 // Append initial segment
609 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
614 // Do recursive conversion
615 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
622 * Recursively convert text on the inside.
624 * @param $text String: text to be converted
625 * @param $variant String: the target variant code
626 * @param $startPos int
627 * @param $depth Integer: depth of recursion
629 * @return String: converted text
631 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
632 // Quick sanity check (no function calls)
633 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
634 throw new MWException( __METHOD__
. ': invalid input string' );
639 $warningDone = false;
640 $length = strlen( $text );
642 while ( $startPos < $length ) {
644 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
654 // Append initial segment
655 $inner .= substr( $text, $startPos, $pos - $startPos );
663 if ( $depth >= $this->mMaxDepth
) {
665 if ( !$warningDone ) {
666 $inner .= '<span class="error">' .
667 wfMsgForContent( 'language-converter-depth-warning',
675 // Recursively parse another rule
676 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
681 $rule = new ConverterRule( $inner, $this );
682 $rule->parse( $variant );
683 $this->applyManualConv( $rule );
684 return $rule->getDisplay();
686 throw new MWException( __METHOD__
. ': invalid regex match' );
691 if ( $startPos < $length ) {
692 $inner .= substr( $text, $startPos );
695 return '-{' . $this->autoConvert( $inner, $variant );
699 * If a language supports multiple variants, it is possible that
700 * non-existing link in one variant actually exists in another variant.
701 * This function tries to find it. See e.g. LanguageZh.php
703 * @param $link String: the name of the link
704 * @param $nt Mixed: the title object of the link
705 * @param $ignoreOtherCond Boolean: to disable other conditions when
706 * we need to transclude a template or update a category's link
707 * @return Null, the input parameters may be modified upon return
709 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
710 # If the article has already existed, there is no need to
711 # check it again, otherwise it may cause a fault.
712 if ( is_object( $nt ) && $nt->exists() ) {
716 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
718 $isredir = $wgRequest->getText( 'redirect', 'yes' );
719 $action = $wgRequest->getText( 'action' );
720 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
721 $disableLinkConversion = $wgDisableLangConversion
722 ||
$wgDisableTitleConversion;
723 $linkBatch = new LinkBatch();
727 if ( $disableLinkConversion ||
728 ( !$ignoreOtherCond &&
731 ||
$action == 'submit'
732 ||
$linkconvert == 'no'
733 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
737 if ( is_object( $nt ) ) {
738 $ns = $nt->getNamespace();
741 $variants = $this->autoConvertToAllVariants( $link );
742 if ( !$variants ) { // give up
748 foreach ( $variants as $v ) {
750 $varnt = Title
::newFromText( $v, $ns );
751 if ( !is_null( $varnt ) ) {
752 $linkBatch->addObj( $varnt );
758 // fetch all variants in single query
759 $linkBatch->execute();
761 foreach ( $titles as $varnt ) {
762 if ( $varnt->getArticleID() > 0 ) {
764 $link = $varnt->getText();
771 * Returns language specific hash options.
775 public function getExtraHashOptions() {
776 $variant = $this->getPreferredVariant();
777 return '!' . $variant;
781 * Guess if a text is written in a variant. This should be implemented in subclasses.
783 * @param string $text the text to be checked
784 * @param string $variant language code of the variant to be checked for
785 * @return bool true if $text appears to be written in $variant, false if not
787 * @author Nikola Smolenski <smolensk@eunet.rs>
790 public function guessVariant($text, $variant) {
795 * Load default conversion tables.
796 * This method must be implemented in derived class.
800 function loadDefaultTables() {
801 $name = get_class( $this );
802 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
806 * Load conversion tables either from the cache or the disk.
808 * @param $fromCache Boolean: load from memcached? Defaults to true.
810 function loadTables( $fromCache = true ) {
811 if ( $this->mTablesLoaded
) {
815 wfProfileIn( __METHOD__
);
816 $this->mTablesLoaded
= true;
817 $this->mTables
= false;
819 wfProfileIn( __METHOD__
. '-cache' );
820 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
821 wfProfileOut( __METHOD__
. '-cache' );
824 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
825 wfProfileIn( __METHOD__
. '-recache' );
826 // not in cache, or we need a fresh reload.
827 // We will first load the default tables
828 // then update them using things in MediaWiki:Conversiontable/*
829 $this->loadDefaultTables();
830 foreach ( $this->mVariants
as $var ) {
831 $cached = $this->parseCachedTable( $var );
832 $this->mTables
[$var]->mergeArray( $cached );
835 $this->postLoadTables();
836 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
838 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
839 wfProfileOut( __METHOD__
. '-recache' );
841 wfProfileOut( __METHOD__
);
845 * Hook for post processing after conversion tables are loaded.
847 function postLoadTables() { }
850 * Reload the conversion tables.
854 function reloadTables() {
855 if ( $this->mTables
) {
856 unset( $this->mTables
);
858 $this->mTablesLoaded
= false;
859 $this->loadTables( false );
863 * Parse the conversion table stored in the cache.
865 * The tables should be in blocks of the following form:
872 * To make the tables more manageable, subpages are allowed
873 * and will be parsed recursively if $recursive == true.
875 * @param $code String: language code
876 * @param $subpage String: subpage name
877 * @param $recursive Boolean: parse subpages recursively? Defaults to true.
881 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
882 static $parsed = array();
884 $key = 'Conversiontable/' . $code;
886 $key .= '/' . $subpage;
888 if ( array_key_exists( $key, $parsed ) ) {
892 if ( strpos( $code, '/' ) === false ) {
893 $txt = MessageCache
::singleton()->get( 'Conversiontable', true, $code );
894 if ( $txt === false ) {
895 # @todo FIXME: This method doesn't seem to be expecting
896 # this possible outcome...
897 $txt = '<Conversiontable>';
900 $title = Title
::makeTitleSafe(
902 "Conversiontable/$code"
904 if ( $title && $title->exists() ) {
905 $article = new Article( $title );
906 $txt = $article->getContents();
912 // get all subpage links of the form
913 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
914 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
916 $subs = StringUtils
::explode( '[[', $txt );
918 foreach ( $subs as $sub ) {
919 $link = explode( ']]', $sub, 2 );
920 if ( count( $link ) != 2 ) {
923 $b = explode( '|', $link[0], 2 );
924 $b = explode( '/', trim( $b[0] ), 3 );
925 if ( count( $b ) == 3 ) {
931 if ( $b[0] == $linkhead && $b[1] == $code ) {
932 $sublinks[] = $sublink;
936 // parse the mappings in this page
937 $blocks = StringUtils
::explode( '-{', $txt );
940 foreach ( $blocks as $block ) {
942 // Skip the part before the first -{
946 $mappings = explode( '}-', $block, 2 );
947 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
949 $table = StringUtils
::explode( ';', $stripped );
950 foreach ( $table as $t ) {
951 $m = explode( '=>', $t, 3 );
952 if ( count( $m ) != 2 ) {
955 // trim any trailling comments starting with '//'
956 $tt = explode( '//', $m[1], 2 );
957 $ret[trim( $m[0] )] = trim( $tt[0] );
960 $parsed[$key] = true;
962 // recursively parse the subpages
964 foreach ( $sublinks as $link ) {
965 $s = $this->parseCachedTable( $code, $link, $recursive );
966 $ret = array_merge( $ret, $s );
970 if ( $this->mUcfirst
) {
971 foreach ( $ret as $k => $v ) {
972 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
979 * Enclose a string with the "no conversion" tag. This is used by
980 * various functions in the Parser.
982 * @param $text String: text to be tagged for no conversion
983 * @param $noParse Boolean: unused
984 * @return String: the tagged text
986 public function markNoConversion( $text, $noParse = false ) {
987 # don't mark if already marked
988 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
992 $ret = "-{R|$text}-";
997 * Convert the sorting key for category links. This should make different
998 * keys that are variants of each other map to the same key.
1000 * @param $key string
1004 function convertCategoryKey( $key ) {
1009 * Hook to refresh the cache of conversion tables when
1010 * MediaWiki:Conversiontable* is updated.
1013 * @param $article Article object
1014 * @param $user Object: User object for the current user
1015 * @param $text String: article text (?)
1016 * @param $summary String: edit summary of the edit
1017 * @param $isMinor Boolean: was the edit marked as minor?
1018 * @param $isWatch Boolean: did the user watch this page or not?
1019 * @param $section Unused
1020 * @param $flags Bitfield
1021 * @param $revision Object: new Revision object or null
1022 * @return Boolean: true
1024 function OnArticleSaveComplete( $article, $user, $text, $summary, $isMinor,
1025 $isWatch, $section, $flags, $revision ) {
1026 $titleobj = $article->getTitle();
1027 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1028 $title = $titleobj->getDBkey();
1029 $t = explode( '/', $title, 3 );
1031 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1032 if ( $this->validateVariant( $t[1] ) ) {
1033 $this->reloadTables();
1041 * Armour rendered math against conversion.
1042 * Escape special chars in parsed math text. (in most cases are img elements)
1044 * @param $text String: text to armour against conversion
1045 * @return String: armoured text where { and } have been converted to
1048 public function armourMath( $text ) {
1049 // convert '-{' and '}-' to '-{' and '}-' to prevent
1050 // any unwanted markup appearing in the math image tag.
1051 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
1056 * Get the cached separator pattern for ConverterRule::parseRules()
1058 function getVarSeparatorPattern() {
1059 if ( is_null( $this->mVarSeparatorPattern
) ) {
1060 // varsep_pattern for preg_split:
1061 // text should be splited by ";" only if a valid variant
1062 // name exist after the markup, for example:
1063 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1064 // <span style="font-size:120%;">yyy</span>;}-
1065 // we should split it as:
1067 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1068 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1072 foreach ( $this->mVariants
as $variant ) {
1073 // zh-hans:xxx;zh-hant:yyy
1074 $pat .= $variant . '\s*:|';
1075 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1076 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1079 $this->mVarSeparatorPattern
= $pat;
1081 return $this->mVarSeparatorPattern
;
1086 * Parser for rules of language conversion , parse rules in -{ }- tag.
1088 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1090 class ConverterRule
{
1091 var $mText; // original text in -{text}-
1092 var $mConverter; // LanguageConverter object
1093 var $mManualCodeError = '<strong class="error">code error!</strong>';
1094 var $mRuleDisplay = '';
1095 var $mRuleTitle = false;
1096 var $mRules = '';// string : the text of the rules
1097 var $mRulesAction = 'none';
1098 var $mFlags = array();
1099 var $mVariantFlags = array();
1100 var $mConvTable = array();
1101 var $mBidtable = array();// array of the translation in each variant
1102 var $mUnidtable = array();// array of the translation in each variant
1107 * @param $text String: the text between -{ and }-
1108 * @param $converter LanguageConverter object
1110 public function __construct( $text, $converter ) {
1111 $this->mText
= $text;
1112 $this->mConverter
= $converter;
1116 * Check if variants array in convert array.
1118 * @param $variants Array or string: variant language code
1119 * @return String: translated text
1121 public function getTextInBidtable( $variants ) {
1122 $variants = (array)$variants;
1126 foreach ( $variants as $variant ) {
1127 if ( isset( $this->mBidtable
[$variant] ) ) {
1128 return $this->mBidtable
[$variant];
1135 * Parse flags with syntax -{FLAG| ... }-
1138 function parseFlags() {
1139 $text = $this->mText
;
1141 $variantFlags = array();
1143 $sepPos = strpos( $text, '|' );
1144 if ( $sepPos !== false ) {
1145 $validFlags = $this->mConverter
->mFlags
;
1146 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1147 foreach ( $f as $ff ) {
1149 if ( isset( $validFlags[$ff] ) ) {
1150 $flags[$validFlags[$ff]] = true;
1153 $text = strval( substr( $text, $sepPos +
1 ) );
1158 } elseif ( isset( $flags['R'] ) ) {
1159 $flags = array( 'R' => true );// remove other flags
1160 } elseif ( isset( $flags['N'] ) ) {
1161 $flags = array( 'N' => true );// remove other flags
1162 } elseif ( isset( $flags['-'] ) ) {
1163 $flags = array( '-' => true );// remove other flags
1164 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1166 } elseif ( isset( $flags['H'] ) ) {
1167 // replace A flag, and remove other flags except T
1168 $temp = array( '+' => true, 'H' => true );
1169 if ( isset( $flags['T'] ) ) {
1172 if ( isset( $flags['D'] ) ) {
1177 if ( isset( $flags['A'] ) ) {
1181 if ( isset( $flags['D'] ) ) {
1182 unset( $flags['S'] );
1184 // try to find flags like "zh-hans", "zh-hant"
1185 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1186 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1187 if ( $variantFlags ) {
1188 $variantFlags = array_flip( $variantFlags );
1192 $this->mVariantFlags
= $variantFlags;
1193 $this->mRules
= $text;
1194 $this->mFlags
= $flags;
1198 * Generate conversion table.
1201 function parseRules() {
1202 $rules = $this->mRules
;
1203 $bidtable = array();
1204 $unidtable = array();
1205 $variants = $this->mConverter
->mVariants
;
1206 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1208 $choice = preg_split( $varsep_pattern, $rules );
1210 foreach ( $choice as $c ) {
1211 $v = explode( ':', $c, 2 );
1212 if ( count( $v ) != 2 ) {
1213 // syntax error, skip
1216 $to = trim( $v[1] );
1218 $u = explode( '=>', $v, 2 );
1219 // if $to is empty, strtr() could return a wrong result
1220 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1221 $bidtable[$v] = $to;
1222 } elseif ( count( $u ) == 2 ) {
1223 $from = trim( $u[0] );
1225 if ( array_key_exists( $v, $unidtable )
1226 && !is_array( $unidtable[$v] )
1228 && in_array( $v, $variants ) ) {
1229 $unidtable[$v] = array( $from => $to );
1230 } elseif ( $to && in_array( $v, $variants ) ) {
1231 $unidtable[$v][$from] = $to;
1234 // syntax error, pass
1235 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1236 $bidtable = array();
1237 $unidtable = array();
1241 $this->mBidtable
= $bidtable;
1242 $this->mUnidtable
= $unidtable;
1250 function getRulesDesc() {
1251 $codesep = $this->mConverter
->mDescCodeSep
;
1252 $varsep = $this->mConverter
->mDescVarSep
;
1254 foreach ( $this->mBidtable
as $k => $v ) {
1255 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1257 foreach ( $this->mUnidtable
as $k => $a ) {
1258 foreach ( $a as $from => $to ) {
1259 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1260 "$codesep$to$varsep";
1267 * Parse rules conversion.
1274 function getRuleConvertedStr( $variant ) {
1275 $bidtable = $this->mBidtable
;
1276 $unidtable = $this->mUnidtable
;
1278 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1279 return $this->mRules
;
1281 // display current variant in bidirectional array
1282 $disp = $this->getTextInBidtable( $variant );
1283 // or display current variant in fallbacks
1285 $disp = $this->getTextInBidtable(
1286 $this->mConverter
->getVariantFallbacks( $variant ) );
1288 // or display current variant in unidirectional array
1289 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1290 $disp = array_values( $unidtable[$variant] );
1293 // or display frist text under disable manual convert
1295 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1296 if ( count( $bidtable ) > 0 ) {
1297 $disp = array_values( $bidtable );
1300 $disp = array_values( $unidtable );
1301 $disp = array_values( $disp[0] );
1310 * Generate conversion table for all text.
1313 function generateConvTable() {
1314 // Special case optimisation
1315 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1316 $this->mConvTable
= array();
1320 $bidtable = $this->mBidtable
;
1321 $unidtable = $this->mUnidtable
;
1322 $manLevel = $this->mConverter
->mManualLevel
;
1325 foreach ( $this->mConverter
->mVariants
as $v ) {
1326 /* for bidirectional array
1327 fill in the missing variants, if any,
1329 if ( !isset( $bidtable[$v] ) ) {
1331 $this->mConverter
->getVariantFallbacks( $v );
1332 $vf = $this->getTextInBidtable( $variantFallbacks );
1334 $bidtable[$v] = $vf;
1338 if ( isset( $bidtable[$v] ) ) {
1339 foreach ( $vmarked as $vo ) {
1340 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1341 // or -{H|zh:WordZh;zh-tw:WordTw}-
1342 // or -{-|zh:WordZh;zh-tw:WordTw}-
1343 // to introduce a custom mapping between
1344 // words WordZh and WordTw in the whole text
1345 if ( $manLevel[$v] == 'bidirectional' ) {
1346 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1348 if ( $manLevel[$vo] == 'bidirectional' ) {
1349 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1354 /* for unidirectional array fill to convert tables */
1355 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1356 && isset( $unidtable[$v] ) )
1358 if ( isset( $this->mConvTable
[$v] ) ) {
1359 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1361 $this->mConvTable
[$v] = $unidtable[$v];
1368 * Parse rules and flags.
1369 * @param $variant String: variant language code
1371 public function parse( $variant = null ) {
1373 $variant = $this->mConverter
->getPreferredVariant();
1376 $this->parseFlags();
1377 $flags = $this->mFlags
;
1379 // convert to specified variant
1380 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1381 if ( $this->mVariantFlags
) {
1382 // check if current variant in flags
1383 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1384 // then convert <text to convert> to current language
1385 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1387 } else { // if current variant no in flags,
1388 // then we check its fallback variants.
1390 $this->mConverter
->getVariantFallbacks( $variant );
1391 if( is_array( $variantFallbacks ) ) {
1392 foreach ( $variantFallbacks as $variantFallback ) {
1393 // if current variant's fallback exist in flags
1394 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1395 // then convert <text to convert> to fallback language
1397 $this->mConverter
->autoConvert( $this->mRules
,
1404 $this->mFlags
= $flags = array( 'R' => true );
1407 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1408 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1409 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1410 $this->parseRules();
1412 $rules = $this->mRules
;
1414 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1415 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1416 // fill all variants if text in -{A/H/-|text} without rules
1417 foreach ( $this->mConverter
->mVariants
as $v ) {
1418 $this->mBidtable
[$v] = $rules;
1420 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1421 $this->mFlags
= $flags = array( 'R' => true );
1425 $this->mRuleDisplay
= false;
1426 foreach ( $flags as $flag => $unused ) {
1429 // if we don't do content convert, still strip the -{}- tags
1430 $this->mRuleDisplay
= $rules;
1433 // process N flag: output current variant name
1434 $ruleVar = trim( $rules );
1435 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1436 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1438 $this->mRuleDisplay
= '';
1442 // process D flag: output rules description
1443 $this->mRuleDisplay
= $this->getRulesDesc();
1446 // process H,- flag or T only: output nothing
1447 $this->mRuleDisplay
= '';
1450 $this->mRulesAction
= 'remove';
1451 $this->mRuleDisplay
= '';
1454 $this->mRulesAction
= 'add';
1455 $this->mRuleDisplay
= '';
1458 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1461 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1462 $this->mRuleDisplay
= '';
1465 // ignore unknown flags (but see error case below)
1468 if ( $this->mRuleDisplay
=== false ) {
1469 $this->mRuleDisplay
= $this->mManualCodeError
;
1472 $this->generateConvTable();
1476 * @todo FIXME: code this function :)
1478 public function hasRules() {
1483 * Get display text on markup -{...}-
1486 public function getDisplay() {
1487 return $this->mRuleDisplay
;
1491 * Get converted title.
1494 public function getTitle() {
1495 return $this->mRuleTitle
;
1499 * Return how deal with conversion rules.
1502 public function getRulesAction() {
1503 return $this->mRulesAction
;
1507 * Get conversion table. (bidirectional and unidirectional
1511 public function getConvTable() {
1512 return $this->mConvTable
;
1516 * Get conversion rules string.
1519 public function getRules() {
1520 return $this->mRules
;
1524 * Get conversion flags.
1527 public function getFlags() {
1528 return $this->mFlags
;