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
{
34 * languages supporting variants
38 static public $languagesWithVariants = array(
49 var $mMainLanguageCode;
50 var $mVariants, $mVariantFallbacks, $mVariantNames;
51 var $mTablesLoaded = false;
53 // 'bidirectional' 'unidirectional' 'disable' for each variant
57 * @var String: memcached key name
63 var $mDescCodeSep = ':', $mDescVarSep = ';';
64 var $mUcfirst = false;
65 var $mConvRuleTitle = false;
70 var $mVarSeparatorPattern;
72 const CACHE_VERSION_KEY
= 'VERSION 6';
77 * @param $langobj Language: the Language Object
78 * @param $maincode String: the main language code of this language
79 * @param $variants Array: the supported variants of this language
80 * @param $variantfallbacks Array: the fallback language of each variant
81 * @param $flags Array: defining the custom strings that maps to the flags
82 * @param $manualLevel Array: limit for supported variants
84 public function __construct( $langobj, $maincode, $variants = array(),
85 $variantfallbacks = array(), $flags = array(),
86 $manualLevel = array() ) {
87 global $wgDisabledVariants;
88 $this->mLangObj
= $langobj;
89 $this->mMainLanguageCode
= $maincode;
90 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
91 $this->mVariantFallbacks
= $variantfallbacks;
92 $this->mVariantNames
= Language
::fetchLanguageNames();
93 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
94 $defaultflags = array(
95 // 'S' show converted text
96 // '+' add rules for alltext
97 // 'E' the gave flags is error
98 // these flags above are reserved for program
99 'A' => 'A', // add rule for convert code (all text convert)
100 'T' => 'T', // title convert
101 'R' => 'R', // raw content
102 'D' => 'D', // convert description (subclass implement)
103 '-' => '-', // remove convert (not implement)
104 'H' => 'H', // add rule for convert code
105 // (but no display in placed code)
106 'N' => 'N' // current variant name
108 $this->mFlags
= array_merge( $defaultflags, $flags );
109 foreach ( $this->mVariants
as $v ) {
110 if ( array_key_exists( $v, $manualLevel ) ) {
111 $this->mManualLevel
[$v] = $manualLevel[$v];
113 $this->mManualLevel
[$v] = 'bidirectional';
115 $this->mFlags
[$v] = $v;
120 * Get all valid variants.
121 * Call this instead of using $this->mVariants directly.
123 * @return Array: contains all valid variants
125 public function getVariants() {
126 return $this->mVariants
;
130 * In case some variant is not defined in the markup, we need
131 * to have some fallback. For example, in zh, normally people
132 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
133 * when zh-sg is preferred but not defined, we will pick zh-hans
134 * in this case. Right now this is only used by zh.
136 * @param $variant String: the language code of the variant
137 * @return String|array: The code of the fallback language or the
138 * main code if there is no fallback
140 public function getVariantFallbacks( $variant ) {
141 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
142 return $this->mVariantFallbacks
[$variant];
144 return $this->mMainLanguageCode
;
148 * Get the title produced by the conversion rule.
149 * @return String: The converted title text
151 public function getConvRuleTitle() {
152 return $this->mConvRuleTitle
;
156 * Get preferred language variant.
157 * @return String: the preferred language code
159 public function getPreferredVariant() {
160 global $wgDefaultLanguageVariant, $wgUser;
162 $req = $this->getURLVariant();
164 if ( $wgUser->isLoggedIn() && !$req ) {
165 $req = $this->getUserVariant();
167 $req = $this->getHeaderVariant();
170 if ( $wgDefaultLanguageVariant && !$req ) {
171 $req = $this->validateVariant( $wgDefaultLanguageVariant );
174 // This function, unlike the other get*Variant functions, is
175 // not memoized (i.e. there return value is not cached) since
176 // new information might appear during processing after this
178 if ( $this->validateVariant( $req ) ) {
181 return $this->mMainLanguageCode
;
185 * Get default variant.
186 * This function would not be affected by user's settings or headers
187 * @return String: the default variant code
189 public function getDefaultVariant() {
190 global $wgDefaultLanguageVariant;
192 $req = $this->getURLVariant();
194 if ( $wgDefaultLanguageVariant && !$req ) {
195 $req = $this->validateVariant( $wgDefaultLanguageVariant );
201 return $this->mMainLanguageCode
;
205 * Validate the variant
206 * @param $variant String: the variant to validate
207 * @return Mixed: returns the variant if it is valid, null otherwise
209 public function validateVariant( $variant = null ) {
210 if ( $variant !== null && in_array( $variant, $this->mVariants
) ) {
217 * Get the variant specified in the URL
219 * @return Mixed: variant if one found, false otherwise.
221 public function getURLVariant() {
224 if ( $this->mURLVariant
) {
225 return $this->mURLVariant
;
228 // see if the preference is set in the request
229 $ret = $wgRequest->getText( 'variant' );
232 $ret = $wgRequest->getVal( 'uselang' );
235 return $this->mURLVariant
= $this->validateVariant( $ret );
239 * Determine if the user has a variant set.
241 * @return Mixed: variant if one found, false otherwise.
243 protected function getUserVariant() {
246 // memoizing this function wreaks havoc on parserTest.php
248 if ( $this->mUserVariant ) {
249 return $this->mUserVariant;
253 // Get language variant preference from logged in users
254 // Don't call this on stub objects because that causes infinite
255 // recursion during initialisation
256 if ( $wgUser->isLoggedIn() ) {
257 $ret = $wgUser->getOption( 'variant' );
259 // figure out user lang without constructing wgLang to avoid
260 // infinite recursion
261 $ret = $wgUser->getOption( 'language' );
264 return $this->mUserVariant
= $this->validateVariant( $ret );
268 * Determine the language variant from the Accept-Language header.
270 * @return Mixed: variant if one found, false otherwise.
272 protected function getHeaderVariant() {
275 if ( $this->mHeaderVariant
) {
276 return $this->mHeaderVariant
;
279 // see if some supported language variant is set in the
281 $languages = array_keys( $wgRequest->getAcceptLang() );
282 if ( empty( $languages ) ) {
286 $fallbackLanguages = array();
287 foreach ( $languages as $language ) {
288 $this->mHeaderVariant
= $this->validateVariant( $language );
289 if ( $this->mHeaderVariant
) {
293 // To see if there are fallbacks of current language.
294 // We record these fallback variants, and process
296 $fallbacks = $this->getVariantFallbacks( $language );
297 if ( is_string( $fallbacks ) ) {
298 $fallbackLanguages[] = $fallbacks;
299 } elseif ( is_array( $fallbacks ) ) {
301 array_merge( $fallbackLanguages, $fallbacks );
305 if ( !$this->mHeaderVariant
) {
306 // process fallback languages now
307 $fallback_languages = array_unique( $fallbackLanguages );
308 foreach ( $fallback_languages as $language ) {
309 $this->mHeaderVariant
= $this->validateVariant( $language );
310 if ( $this->mHeaderVariant
) {
316 return $this->mHeaderVariant
;
320 * Dictionary-based conversion.
321 * This function would not parse the conversion rules.
322 * If you want to parse rules, try to use convert() or
325 * @param $text String the text to be converted
326 * @param $toVariant bool|string the target language code
327 * @return String the converted text
329 public function autoConvert( $text, $toVariant = false ) {
330 wfProfileIn( __METHOD__
);
335 $toVariant = $this->getPreferredVariant();
337 wfProfileOut( __METHOD__
);
342 if( $this->guessVariant( $text, $toVariant ) ) {
343 wfProfileOut( __METHOD__
);
347 /* we convert everything except:
348 1. HTML markups (anything between < and >)
350 3. placeholders created by the parser
353 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
354 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
359 // this one is needed when the text is inside an HTML markup
360 $htmlfix = '|<[^>]+$|^[^<>]*>';
362 // disable convert to variants between <code></code> tags
363 $codefix = '<code>.+?<\/code>|';
364 // disable convertsion of <script type="text/javascript"> ... </script>
365 $scriptfix = '<script.*?>.*?<\/script>|';
366 // disable conversion of <pre xxxx> ... </pre>
367 $prefix = '<pre.*?>.*?<\/pre>|';
369 $reg = '/' . $codefix . $scriptfix . $prefix .
370 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
375 // Guard against delimiter nulls in the input
376 $text = str_replace( "\000", '', $text );
378 $markupMatches = null;
379 $elementMatches = null;
380 while ( $startPos < strlen( $text ) ) {
381 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE
, $startPos ) ) {
382 $elementPos = $markupMatches[0][1];
383 $element = $markupMatches[0][0];
385 $elementPos = strlen( $text );
389 // Queue the part before the markup for translation in a batch
390 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
392 // Advance to the next position
393 $startPos = $elementPos +
strlen( $element );
395 // Translate any alt or title attributes inside the matched element
396 if ( $element !== '' && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element,
399 $attrs = Sanitizer
::decodeTagAttributes( $elementMatches[2] );
401 foreach ( array( 'title', 'alt' ) as $attrName ) {
402 if ( !isset( $attrs[$attrName] ) ) {
405 $attr = $attrs[$attrName];
406 // Don't convert URLs
407 if ( !strpos( $attr, '://' ) ) {
408 $attr = $this->translate( $attr, $toVariant );
411 // Remove HTML tags to avoid disrupting the layout
412 $attr = preg_replace( '/<[^>]+>/', '', $attr );
413 if ( $attr !== $attrs[$attrName] ) {
414 $attrs[$attrName] = $attr;
419 $element = $elementMatches[1] . Html
::expandAttributes( $attrs ) .
423 $literalBlob .= $element . "\000";
426 // Do the main translation batch
427 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
429 // Put the output back together
430 $translatedIter = StringUtils
::explode( "\000", $translatedBlob );
431 $literalIter = StringUtils
::explode( "\000", $literalBlob );
433 while ( $translatedIter->valid() && $literalIter->valid() ) {
434 $output .= $translatedIter->current();
435 $output .= $literalIter->current();
436 $translatedIter->next();
437 $literalIter->next();
440 wfProfileOut( __METHOD__
);
445 * Translate a string to a variant.
446 * Doesn't parse rules or do any of that other stuff, for that use
447 * convert() or convertTo().
449 * @param $text String: text to convert
450 * @param $variant String: variant language code
451 * @return String: translated text
453 public function translate( $text, $variant ) {
454 wfProfileIn( __METHOD__
);
455 // If $text is empty or only includes spaces, do nothing
456 // Otherwise translate it
457 if ( trim( $text ) ) {
459 $text = $this->mTables
[$variant]->replace( $text );
461 wfProfileOut( __METHOD__
);
466 * Call translate() to convert text to all valid variants.
468 * @param $text String: the text to be converted
469 * @return Array: variant => converted text
471 public function autoConvertToAllVariants( $text ) {
472 wfProfileIn( __METHOD__
);
476 foreach ( $this->mVariants
as $variant ) {
477 $ret[$variant] = $this->translate( $text, $variant );
480 wfProfileOut( __METHOD__
);
485 * Convert link text to all valid variants.
486 * In the first, this function only convert text outside the
487 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
488 * titles, the text will get all converted always.
489 * So I removed this feature and deprecated the function.
491 * @param $text String: the text to be converted
492 * @return Array: variant => converted text
493 * @deprecated since 1.17 Use autoConvertToAllVariants() instead
495 public function convertLinkToAllVariants( $text ) {
496 return $this->autoConvertToAllVariants( $text );
500 * Apply manual conversion rules.
502 * @param $convRule ConverterRule Object of ConverterRule
504 protected function applyManualConv( $convRule ) {
505 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
507 // Bug 24072: $mConvRuleTitle was overwritten by other manual
508 // rule(s) not for title, this breaks the title conversion.
509 $newConvRuleTitle = $convRule->getTitle();
510 if ( $newConvRuleTitle ) {
511 // So I add an empty check for getTitle()
512 $this->mConvRuleTitle
= $newConvRuleTitle;
515 // merge/remove manual conversion rules to/from global table
516 $convTable = $convRule->getConvTable();
517 $action = $convRule->getRulesAction();
518 foreach ( $convTable as $variant => $pair ) {
519 if ( !$this->validateVariant( $variant ) ) {
523 if ( $action == 'add' ) {
524 foreach ( $pair as $from => $to ) {
525 // to ensure that $from and $to not be left blank
526 // so $this->translate() could always return a string
527 if ( $from ||
$to ) {
528 // more efficient than array_merge(), about 2.5 times.
529 $this->mTables
[$variant]->setPair( $from, $to );
532 } elseif ( $action == 'remove' ) {
533 $this->mTables
[$variant]->removeArray( $pair );
539 * Auto convert a Title object to a readable string in the
542 * @param $title Title a object of Title
543 * @return String: converted title text
545 public function convertTitle( $title ) {
546 $variant = $this->getPreferredVariant();
547 $index = $title->getNamespace();
548 if ( $index === NS_MAIN
) {
551 // first let's check if a message has given us a converted name
552 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
553 if ( $nsConvMsg->exists() ) {
554 $text = $nsConvMsg->plain();
556 // the message does not exist, try retrieve it from the current
557 // variant's namespace names.
558 $langObj = $this->mLangObj
->factory( $variant );
559 $text = $langObj->getFormattedNsText( $index );
563 $text .= $title->getText();
564 $text = $this->translate( $text, $variant );
569 * Convert text to different variants of a language. The automatic
570 * conversion is done in autoConvert(). Here we parse the text
571 * marked with -{}-, which specifies special conversions of the
572 * text that can not be accomplished in autoConvert().
574 * Syntax of the markup:
575 * -{code1:text1;code2:text2;...}- or
576 * -{flags|code1:text1;code2:text2;...}- or
577 * -{text}- in which case no conversion should take place for text
579 * @param $text String: text to be converted
580 * @return String: converted text
582 public function convert( $text ) {
583 $variant = $this->getPreferredVariant();
584 return $this->convertTo( $text, $variant );
588 * Same as convert() except a extra parameter to custom variant.
590 * @param $text String: text to be converted
591 * @param $variant String: the target variant code
592 * @return String: converted text
594 public function convertTo( $text, $variant ) {
595 global $wgDisableLangConversion;
596 if ( $wgDisableLangConversion ) {
599 return $this->recursiveConvertTopLevel( $text, $variant );
603 * Recursively convert text on the outside. Allow to use nested
604 * markups to custom rules.
606 * @param $text String: text to be converted
607 * @param $variant String: the target variant code
608 * @param $depth Integer: depth of recursion
609 * @return String: converted text
611 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
614 $length = strlen( $text );
615 $shouldConvert = !$this->guessVariant( $text, $variant );
617 while ( $startPos < $length ) {
618 $pos = strpos( $text, '-{', $startPos );
620 if ( $pos === false ) {
621 // No more markup, append final segment
622 $fragment = substr( $text, $startPos );
623 $out .= $shouldConvert?
$this->autoConvert( $fragment, $variant ): $fragment;
628 // Append initial segment
629 $fragment = substr( $text, $startPos, $pos - $startPos );
630 $out .= $shouldConvert?
$this->autoConvert( $fragment, $variant ): $fragment;
635 // Do recursive conversion
636 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
643 * Recursively convert text on the inside.
645 * @param $text String: text to be converted
646 * @param $variant String: the target variant code
647 * @param $startPos int
648 * @param $depth Integer: depth of recursion
650 * @throws MWException
651 * @return String: converted text
653 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
654 // Quick sanity check (no function calls)
655 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
656 throw new MWException( __METHOD__
. ': invalid input string' );
661 $warningDone = false;
662 $length = strlen( $text );
664 while ( $startPos < $length ) {
666 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
676 // Append initial segment
677 $inner .= substr( $text, $startPos, $pos - $startPos );
685 if ( $depth >= $this->mMaxDepth
) {
687 if ( !$warningDone ) {
688 $inner .= '<span class="error">' .
689 wfMsgForContent( 'language-converter-depth-warning',
697 // Recursively parse another rule
698 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
703 $rule = new ConverterRule( $inner, $this );
704 $rule->parse( $variant );
705 $this->applyManualConv( $rule );
706 return $rule->getDisplay();
708 throw new MWException( __METHOD__
. ': invalid regex match' );
713 if ( $startPos < $length ) {
714 $inner .= substr( $text, $startPos );
717 return '-{' . $this->autoConvert( $inner, $variant );
721 * If a language supports multiple variants, it is possible that
722 * non-existing link in one variant actually exists in another variant.
723 * This function tries to find it. See e.g. LanguageZh.php
725 * @param $link String: the name of the link
726 * @param $nt Mixed: the title object of the link
727 * @param $ignoreOtherCond Boolean: to disable other conditions when
728 * we need to transclude a template or update a category's link
729 * @return Null, the input parameters may be modified upon return
731 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
732 # If the article has already existed, there is no need to
733 # check it again, otherwise it may cause a fault.
734 if ( is_object( $nt ) && $nt->exists() ) {
738 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
740 $isredir = $wgRequest->getText( 'redirect', 'yes' );
741 $action = $wgRequest->getText( 'action' );
742 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
743 $disableLinkConversion = $wgDisableLangConversion
744 ||
$wgDisableTitleConversion;
745 $linkBatch = new LinkBatch();
749 if ( $disableLinkConversion ||
750 ( !$ignoreOtherCond &&
753 ||
$action == 'submit'
754 ||
$linkconvert == 'no'
755 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
759 if ( is_object( $nt ) ) {
760 $ns = $nt->getNamespace();
763 $variants = $this->autoConvertToAllVariants( $link );
764 if ( !$variants ) { // give up
770 foreach ( $variants as $v ) {
772 $varnt = Title
::newFromText( $v, $ns );
773 if ( !is_null( $varnt ) ) {
774 $linkBatch->addObj( $varnt );
780 // fetch all variants in single query
781 $linkBatch->execute();
783 foreach ( $titles as $varnt ) {
784 if ( $varnt->getArticleID() > 0 ) {
786 $link = $varnt->getText();
793 * Returns language specific hash options.
797 public function getExtraHashOptions() {
798 $variant = $this->getPreferredVariant();
799 return '!' . $variant;
803 * Guess if a text is written in a variant. This should be implemented in subclasses.
805 * @param string $text the text to be checked
806 * @param string $variant language code of the variant to be checked for
807 * @return bool true if $text appears to be written in $variant, false if not
809 * @author Nikola Smolenski <smolensk@eunet.rs>
812 public function guessVariant($text, $variant) {
817 * Load default conversion tables.
818 * This method must be implemented in derived class.
821 * @throws MWException
823 function loadDefaultTables() {
824 $name = get_class( $this );
825 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
829 * Load conversion tables either from the cache or the disk.
831 * @param $fromCache Boolean: load from memcached? Defaults to true.
833 function loadTables( $fromCache = true ) {
834 global $wgLangConvMemc;
836 if ( $this->mTablesLoaded
) {
840 wfProfileIn( __METHOD__
);
841 $this->mTablesLoaded
= true;
842 $this->mTables
= false;
844 wfProfileIn( __METHOD__
. '-cache' );
845 $this->mTables
= $wgLangConvMemc->get( $this->mCacheKey
);
846 wfProfileOut( __METHOD__
. '-cache' );
849 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
850 wfProfileIn( __METHOD__
. '-recache' );
851 // not in cache, or we need a fresh reload.
852 // We will first load the default tables
853 // then update them using things in MediaWiki:Conversiontable/*
854 $this->loadDefaultTables();
855 foreach ( $this->mVariants
as $var ) {
856 $cached = $this->parseCachedTable( $var );
857 $this->mTables
[$var]->mergeArray( $cached );
860 $this->postLoadTables();
861 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
863 $wgLangConvMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
864 wfProfileOut( __METHOD__
. '-recache' );
866 wfProfileOut( __METHOD__
);
870 * Hook for post processing after conversion tables are loaded.
872 function postLoadTables() { }
875 * Reload the conversion tables.
879 function reloadTables() {
880 if ( $this->mTables
) {
881 unset( $this->mTables
);
883 $this->mTablesLoaded
= false;
884 $this->loadTables( false );
888 * Parse the conversion table stored in the cache.
890 * The tables should be in blocks of the following form:
897 * To make the tables more manageable, subpages are allowed
898 * and will be parsed recursively if $recursive == true.
900 * @param $code String: language code
901 * @param $subpage String: subpage name
902 * @param $recursive Boolean: parse subpages recursively? Defaults to true.
906 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
907 static $parsed = array();
909 $key = 'Conversiontable/' . $code;
911 $key .= '/' . $subpage;
913 if ( array_key_exists( $key, $parsed ) ) {
917 $parsed[$key] = true;
919 if ( $subpage === '' ) {
920 $txt = MessageCache
::singleton()->get( 'conversiontable', true, $code );
923 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
, $key );
924 if ( $title && $title->exists() ) {
925 $revision = Revision
::newFromTitle( $title );
927 $txt = $revision->getRawText();
932 # Nothing to parse if there's no text
933 if ( $txt === false ||
$txt === null ||
$txt === '' ) {
937 // get all subpage links of the form
938 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
939 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
941 $subs = StringUtils
::explode( '[[', $txt );
943 foreach ( $subs as $sub ) {
944 $link = explode( ']]', $sub, 2 );
945 if ( count( $link ) != 2 ) {
948 $b = explode( '|', $link[0], 2 );
949 $b = explode( '/', trim( $b[0] ), 3 );
950 if ( count( $b ) == 3 ) {
956 if ( $b[0] == $linkhead && $b[1] == $code ) {
957 $sublinks[] = $sublink;
961 // parse the mappings in this page
962 $blocks = StringUtils
::explode( '-{', $txt );
965 foreach ( $blocks as $block ) {
967 // Skip the part before the first -{
971 $mappings = explode( '}-', $block, 2 );
972 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
974 $table = StringUtils
::explode( ';', $stripped );
975 foreach ( $table as $t ) {
976 $m = explode( '=>', $t, 3 );
977 if ( count( $m ) != 2 ) {
980 // trim any trailling comments starting with '//'
981 $tt = explode( '//', $m[1], 2 );
982 $ret[trim( $m[0] )] = trim( $tt[0] );
986 // recursively parse the subpages
988 foreach ( $sublinks as $link ) {
989 $s = $this->parseCachedTable( $code, $link, $recursive );
990 $ret = array_merge( $ret, $s );
994 if ( $this->mUcfirst
) {
995 foreach ( $ret as $k => $v ) {
996 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
1003 * Enclose a string with the "no conversion" tag. This is used by
1004 * various functions in the Parser.
1006 * @param $text String: text to be tagged for no conversion
1007 * @param $noParse Boolean: unused
1008 * @return String: the tagged text
1010 public function markNoConversion( $text, $noParse = false ) {
1011 # don't mark if already marked
1012 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
1016 $ret = "-{R|$text}-";
1021 * Convert the sorting key for category links. This should make different
1022 * keys that are variants of each other map to the same key.
1024 * @param $key string
1028 function convertCategoryKey( $key ) {
1033 * Hook to refresh the cache of conversion tables when
1034 * MediaWiki:Conversiontable* is updated.
1037 * @param $article Article object
1038 * @param $user Object: User object for the current user
1039 * @param $text String: article text (?)
1040 * @param $summary String: edit summary of the edit
1041 * @param $isMinor Boolean: was the edit marked as minor?
1042 * @param $isWatch Boolean: did the user watch this page or not?
1044 * @param $flags int Bitfield
1045 * @param $revision Object: new Revision object or null
1046 * @return Boolean: true
1048 function OnArticleSaveComplete( $article, $user, $text, $summary, $isMinor,
1049 $isWatch, $section, $flags, $revision ) {
1050 $titleobj = $article->getTitle();
1051 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
1052 $title = $titleobj->getDBkey();
1053 $t = explode( '/', $title, 3 );
1055 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1056 if ( $this->validateVariant( $t[1] ) ) {
1057 $this->reloadTables();
1065 * Armour rendered math against conversion.
1066 * Escape special chars in parsed math text. (in most cases are img elements)
1068 * @param $text String: text to armour against conversion
1069 * @return String: armoured text where { and } have been converted to
1072 public function armourMath( $text ) {
1073 // convert '-{' and '}-' to '-{' and '}-' to prevent
1074 // any unwanted markup appearing in the math image tag.
1075 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
1080 * Get the cached separator pattern for ConverterRule::parseRules()
1082 function getVarSeparatorPattern() {
1083 if ( is_null( $this->mVarSeparatorPattern
) ) {
1084 // varsep_pattern for preg_split:
1085 // text should be splited by ";" only if a valid variant
1086 // name exist after the markup, for example:
1087 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1088 // <span style="font-size:120%;">yyy</span>;}-
1089 // we should split it as:
1091 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1092 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1096 foreach ( $this->mVariants
as $variant ) {
1097 // zh-hans:xxx;zh-hant:yyy
1098 $pat .= $variant . '\s*:|';
1099 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1100 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1103 $this->mVarSeparatorPattern
= $pat;
1105 return $this->mVarSeparatorPattern
;
1110 * Parser for rules of language conversion , parse rules in -{ }- tag.
1112 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1114 class ConverterRule
{
1115 var $mText; // original text in -{text}-
1116 var $mConverter; // LanguageConverter object
1117 var $mManualCodeError = '<strong class="error">code error!</strong>';
1118 var $mRuleDisplay = '';
1119 var $mRuleTitle = false;
1120 var $mRules = '';// string : the text of the rules
1121 var $mRulesAction = 'none';
1122 var $mFlags = array();
1123 var $mVariantFlags = array();
1124 var $mConvTable = array();
1125 var $mBidtable = array();// array of the translation in each variant
1126 var $mUnidtable = array();// array of the translation in each variant
1131 * @param $text String: the text between -{ and }-
1132 * @param $converter LanguageConverter object
1134 public function __construct( $text, $converter ) {
1135 $this->mText
= $text;
1136 $this->mConverter
= $converter;
1140 * Check if variants array in convert array.
1142 * @param $variants Array or string: variant language code
1143 * @return String: translated text
1145 public function getTextInBidtable( $variants ) {
1146 $variants = (array)$variants;
1150 foreach ( $variants as $variant ) {
1151 if ( isset( $this->mBidtable
[$variant] ) ) {
1152 return $this->mBidtable
[$variant];
1159 * Parse flags with syntax -{FLAG| ... }-
1162 function parseFlags() {
1163 $text = $this->mText
;
1165 $variantFlags = array();
1167 $sepPos = strpos( $text, '|' );
1168 if ( $sepPos !== false ) {
1169 $validFlags = $this->mConverter
->mFlags
;
1170 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1171 foreach ( $f as $ff ) {
1173 if ( isset( $validFlags[$ff] ) ) {
1174 $flags[$validFlags[$ff]] = true;
1177 $text = strval( substr( $text, $sepPos +
1 ) );
1182 } elseif ( isset( $flags['R'] ) ) {
1183 $flags = array( 'R' => true );// remove other flags
1184 } elseif ( isset( $flags['N'] ) ) {
1185 $flags = array( 'N' => true );// remove other flags
1186 } elseif ( isset( $flags['-'] ) ) {
1187 $flags = array( '-' => true );// remove other flags
1188 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1190 } elseif ( isset( $flags['H'] ) ) {
1191 // replace A flag, and remove other flags except T
1192 $temp = array( '+' => true, 'H' => true );
1193 if ( isset( $flags['T'] ) ) {
1196 if ( isset( $flags['D'] ) ) {
1201 if ( isset( $flags['A'] ) ) {
1205 if ( isset( $flags['D'] ) ) {
1206 unset( $flags['S'] );
1208 // try to find flags like "zh-hans", "zh-hant"
1209 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1210 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1211 if ( $variantFlags ) {
1212 $variantFlags = array_flip( $variantFlags );
1216 $this->mVariantFlags
= $variantFlags;
1217 $this->mRules
= $text;
1218 $this->mFlags
= $flags;
1222 * Generate conversion table.
1225 function parseRules() {
1226 $rules = $this->mRules
;
1227 $bidtable = array();
1228 $unidtable = array();
1229 $variants = $this->mConverter
->mVariants
;
1230 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1232 $choice = preg_split( $varsep_pattern, $rules );
1234 foreach ( $choice as $c ) {
1235 $v = explode( ':', $c, 2 );
1236 if ( count( $v ) != 2 ) {
1237 // syntax error, skip
1240 $to = trim( $v[1] );
1242 $u = explode( '=>', $v, 2 );
1243 // if $to is empty, strtr() could return a wrong result
1244 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1245 $bidtable[$v] = $to;
1246 } elseif ( count( $u ) == 2 ) {
1247 $from = trim( $u[0] );
1249 if ( array_key_exists( $v, $unidtable )
1250 && !is_array( $unidtable[$v] )
1252 && in_array( $v, $variants ) ) {
1253 $unidtable[$v] = array( $from => $to );
1254 } elseif ( $to && in_array( $v, $variants ) ) {
1255 $unidtable[$v][$from] = $to;
1258 // syntax error, pass
1259 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1260 $bidtable = array();
1261 $unidtable = array();
1265 $this->mBidtable
= $bidtable;
1266 $this->mUnidtable
= $unidtable;
1274 function getRulesDesc() {
1275 $codesep = $this->mConverter
->mDescCodeSep
;
1276 $varsep = $this->mConverter
->mDescVarSep
;
1278 foreach ( $this->mBidtable
as $k => $v ) {
1279 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1281 foreach ( $this->mUnidtable
as $k => $a ) {
1282 foreach ( $a as $from => $to ) {
1283 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1284 "$codesep$to$varsep";
1291 * Parse rules conversion.
1298 function getRuleConvertedStr( $variant ) {
1299 $bidtable = $this->mBidtable
;
1300 $unidtable = $this->mUnidtable
;
1302 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1303 return $this->mRules
;
1305 // display current variant in bidirectional array
1306 $disp = $this->getTextInBidtable( $variant );
1307 // or display current variant in fallbacks
1309 $disp = $this->getTextInBidtable(
1310 $this->mConverter
->getVariantFallbacks( $variant ) );
1312 // or display current variant in unidirectional array
1313 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1314 $disp = array_values( $unidtable[$variant] );
1317 // or display frist text under disable manual convert
1319 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1320 if ( count( $bidtable ) > 0 ) {
1321 $disp = array_values( $bidtable );
1324 $disp = array_values( $unidtable );
1325 $disp = array_values( $disp[0] );
1334 * Generate conversion table for all text.
1337 function generateConvTable() {
1338 // Special case optimisation
1339 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1340 $this->mConvTable
= array();
1344 $bidtable = $this->mBidtable
;
1345 $unidtable = $this->mUnidtable
;
1346 $manLevel = $this->mConverter
->mManualLevel
;
1349 foreach ( $this->mConverter
->mVariants
as $v ) {
1350 /* for bidirectional array
1351 fill in the missing variants, if any,
1353 if ( !isset( $bidtable[$v] ) ) {
1355 $this->mConverter
->getVariantFallbacks( $v );
1356 $vf = $this->getTextInBidtable( $variantFallbacks );
1358 $bidtable[$v] = $vf;
1362 if ( isset( $bidtable[$v] ) ) {
1363 foreach ( $vmarked as $vo ) {
1364 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1365 // or -{H|zh:WordZh;zh-tw:WordTw}-
1366 // or -{-|zh:WordZh;zh-tw:WordTw}-
1367 // to introduce a custom mapping between
1368 // words WordZh and WordTw in the whole text
1369 if ( $manLevel[$v] == 'bidirectional' ) {
1370 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1372 if ( $manLevel[$vo] == 'bidirectional' ) {
1373 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1378 /* for unidirectional array fill to convert tables */
1379 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1380 && isset( $unidtable[$v] ) )
1382 if ( isset( $this->mConvTable
[$v] ) ) {
1383 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1385 $this->mConvTable
[$v] = $unidtable[$v];
1392 * Parse rules and flags.
1393 * @param $variant String: variant language code
1395 public function parse( $variant = null ) {
1397 $variant = $this->mConverter
->getPreferredVariant();
1400 $this->parseFlags();
1401 $flags = $this->mFlags
;
1403 // convert to specified variant
1404 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1405 if ( $this->mVariantFlags
) {
1406 // check if current variant in flags
1407 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1408 // then convert <text to convert> to current language
1409 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1411 } else { // if current variant no in flags,
1412 // then we check its fallback variants.
1414 $this->mConverter
->getVariantFallbacks( $variant );
1415 if( is_array( $variantFallbacks ) ) {
1416 foreach ( $variantFallbacks as $variantFallback ) {
1417 // if current variant's fallback exist in flags
1418 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1419 // then convert <text to convert> to fallback language
1421 $this->mConverter
->autoConvert( $this->mRules
,
1428 $this->mFlags
= $flags = array( 'R' => true );
1431 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1432 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1433 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1434 $this->parseRules();
1436 $rules = $this->mRules
;
1438 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1439 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1440 // fill all variants if text in -{A/H/-|text} without rules
1441 foreach ( $this->mConverter
->mVariants
as $v ) {
1442 $this->mBidtable
[$v] = $rules;
1444 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1445 $this->mFlags
= $flags = array( 'R' => true );
1449 $this->mRuleDisplay
= false;
1450 foreach ( $flags as $flag => $unused ) {
1453 // if we don't do content convert, still strip the -{}- tags
1454 $this->mRuleDisplay
= $rules;
1457 // process N flag: output current variant name
1458 $ruleVar = trim( $rules );
1459 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1460 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1462 $this->mRuleDisplay
= '';
1466 // process D flag: output rules description
1467 $this->mRuleDisplay
= $this->getRulesDesc();
1470 // process H,- flag or T only: output nothing
1471 $this->mRuleDisplay
= '';
1474 $this->mRulesAction
= 'remove';
1475 $this->mRuleDisplay
= '';
1478 $this->mRulesAction
= 'add';
1479 $this->mRuleDisplay
= '';
1482 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1485 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1486 $this->mRuleDisplay
= '';
1489 // ignore unknown flags (but see error case below)
1492 if ( $this->mRuleDisplay
=== false ) {
1493 $this->mRuleDisplay
= $this->mManualCodeError
;
1496 $this->generateConvTable();
1500 * @todo FIXME: code this function :)
1502 public function hasRules() {
1507 * Get display text on markup -{...}-
1510 public function getDisplay() {
1511 return $this->mRuleDisplay
;
1515 * Get converted title.
1518 public function getTitle() {
1519 return $this->mRuleTitle
;
1523 * Return how deal with conversion rules.
1526 public function getRulesAction() {
1527 return $this->mRulesAction
;
1531 * Get conversion table. (bidirectional and unidirectional
1535 public function getConvTable() {
1536 return $this->mConvTable
;
1540 * Get conversion rules string.
1543 public function getRules() {
1544 return $this->mRules
;
1548 * Get conversion flags.
1551 public function getFlags() {
1552 return $this->mFlags
;