4 * Contains the LanguageConverter class and ConverterRule class
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
12 * Base class for language conversion.
15 * @author Zhengzhu Feng <zhengzhu@gmail.com>
16 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>, PhiLiP <philip.npc@gmail.com>
18 class LanguageConverter
{
19 var $mMainLanguageCode;
20 var $mVariants, $mVariantFallbacks, $mVariantNames;
21 var $mTablesLoaded = false;
23 // 'bidirectional' 'unidirectional' 'disable' for each variant
28 var $mDescCodeSep = ':', $mDescVarSep = ';';
29 var $mUcfirst = false;
30 var $mConvRuleTitle = false;
35 var $mVarSeparatorPattern;
37 const CACHE_VERSION_KEY
= 'VERSION 6';
42 * @param $langobj The Language Object
43 * @param $maincode String: the main language code of this language
44 * @param $variants Array: the supported variants of this language
45 * @param $variantfallbacks Array: the fallback language of each variant
46 * @param $flags Array: defining the custom strings that maps to the flags
47 * @param $manualLevel Array: limit for supported variants
49 public function __construct( $langobj, $maincode,
51 $variantfallbacks = array(),
53 $manualLevel = array() ) {
54 global $wgDisabledVariants, $wgLanguageNames;
55 $this->mLangObj
= $langobj;
56 $this->mMainLanguageCode
= $maincode;
57 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
58 $this->mVariantFallbacks
= $variantfallbacks;
59 $this->mVariantNames
= $wgLanguageNames;
60 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
61 $defaultflags = array(
62 // 'S' show converted text
63 // '+' add rules for alltext
64 // 'E' the gave flags is error
65 // these flags above are reserved for program
66 'A' => 'A', // add rule for convert code (all text convert)
67 'T' => 'T', // title convert
68 'R' => 'R', // raw content
69 'D' => 'D', // convert description (subclass implement)
70 '-' => '-', // remove convert (not implement)
71 'H' => 'H', // add rule for convert code
72 // (but no display in placed code )
73 'N' => 'N' // current variant name
75 $this->mFlags
= array_merge( $defaultflags, $flags );
76 foreach ( $this->mVariants
as $v ) {
77 if ( array_key_exists( $v, $manualLevel ) ) {
78 $this->mManualLevel
[$v] = $manualLevel[$v];
80 $this->mManualLevel
[$v] = 'bidirectional';
82 $this->mFlags
[$v] = $v;
87 * Get all valid variants.
88 * Call this instead of using $this->mVariants directly.
90 * @return Array: contains all valid variants
92 public function getVariants() {
93 return $this->mVariants
;
97 * In case some variant is not defined in the markup, we need
98 * to have some fallback. For example, in zh, normally people
99 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
100 * when zh-sg is preferred but not defined, we will pick zh-hans
101 * in this case. Right now this is only used by zh.
103 * @param $variant String: the language code of the variant
104 * @return String: The code of the fallback language or the
105 * main code if there is no fallback
107 public function getVariantFallbacks( $variant ) {
108 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
109 return $this->mVariantFallbacks
[$variant];
111 return $this->mMainLanguageCode
;
115 * Get the title produced by the conversion rule.
116 * @return String: The converted title text
118 public function getConvRuleTitle() {
119 return $this->mConvRuleTitle
;
123 * Get preferred language variant.
124 * @param $fromUser Boolean: get it from $wgUser's preferences
125 * @param $fromHeader Boolean: get it from Accept-Language
126 * @return String: the preferred language code
128 public function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
129 global $wgDefaultLanguageVariant;
131 $req = $this->getURLVariant();
133 if ( $fromUser && !$req ) {
134 $req = $this->getUserVariant();
137 if ( $fromHeader && !$req ) {
138 $req = $this->getHeaderVariant();
141 if ( $wgDefaultLanguageVariant && !$req ) {
142 $req = $this->validateVariant( $wgDefaultLanguageVariant );
145 // This function, unlike the other get*Variant functions, is
146 // not memoized (i.e. there return value is not cached) since
147 // new information might appear during processing after this
152 return $this->mMainLanguageCode
;
156 * Validate the variant
157 * @param $variant String: the variant to validate
158 * @return Mixed: returns the variant if it is valid, null otherwise
160 protected function validateVariant( $variant = null ) {
161 if ( $variant !== null &&
162 in_array( $variant, $this->mVariants
) ) {
169 * Get the variant specified in the URL
171 * @return Mixed: variant if one found, false otherwise.
173 protected function getURLVariant() {
177 if ( $this->mURLVariant
) {
178 return $this->mURLVariant
;
181 // see if the preference is set in the request
182 $ret = $wgRequest->getText( 'variant' );
185 $ret = $wgRequest->getVal( 'uselang' );
188 return $this->mURLVariant
= $this->validateVariant( $ret );
192 * Determine if the user has a variant set.
194 * @return Mixed: variant if one found, false otherwise.
196 protected function getUserVariant() {
200 // memoizing this function wreaks havoc on parserTest.php
201 /* if ( $this->mUserVariant ) { */
202 /* return $this->mUserVariant; */
205 // get language variant preference from logged in users
206 // Don't call this on stub objects because that causes infinite
207 // recursion during initialisation
208 if ( $wgUser->isLoggedIn() ) {
209 $ret = $wgUser->getOption( 'variant' );
212 // figure out user lang without constructing wgLang to avoid
213 // infinite recursion
214 $ret = $wgUser->getOption( 'language' );
217 return $this->mUserVariant
= $this->validateVariant( $ret );
222 * Determine the language variant from the Accept-Language header.
224 * @return Mixed: variant if one found, false otherwise.
226 protected function getHeaderVariant() {
230 if ( $this->mHeaderVariant
) {
231 return $this->mHeaderVariant
;
234 // see if some supported language variant is set in the
236 $acceptLanguage = $wgRequest->getHeader( 'Accept-Language' );
237 if ( !$acceptLanguage ) {
242 $result = StringUtils
::explode( ',', strtolower( $acceptLanguage ) );
243 $languages = array();
245 foreach ( $result as $elem ) {
246 // if $elem likes 'zh-cn;q=0.9'
247 if ( ( $posi = strpos( $elem, ';' ) ) !== false ) {
248 // get the real language code likes 'zh-cn'
249 $languages[] = substr( $elem, 0, $posi );
251 $languages[] = $elem;
255 $fallback_languages = array();
256 foreach ( $languages as $language ) {
258 $language = trim( $language );
259 $this->mHeaderVariant
= $this->validateVariant( $language );
260 if ( $this->mHeaderVariant
) {
264 // To see if there are fallbacks of current language.
265 // We record these fallback variants, and process
267 $fallbacks = $this->getVariantFallbacks( $language );
268 if ( is_string( $fallbacks ) ) {
269 $fallback_languages[] = $fallbacks;
270 } elseif ( is_array( $fallbacks ) ) {
271 $fallback_languages =
272 array_merge( $fallback_languages,
277 if ( !$this->mHeaderVariant
) {
278 // process fallback languages now
279 $fallback_languages = array_unique( $fallback_languages );
280 foreach ( $fallback_languages as $language ) {
281 $this->mHeaderVariant
= $this->validateVariant( $language );
282 if ( $this->mHeaderVariant
) {
288 return $this->mHeaderVariant
;
292 * Caption convert, base on preg_replace_callback.
294 * To convert text in "title" or "alt", like '<img alt="text" ... '
295 * or '<span title="text" ... '
297 * @return String like ' alt="yyyy"' or ' title="yyyy"'
299 protected function captionConvert( $matches ) {
300 $toVariant = $this->getPreferredVariant();
301 $title = $matches[1];
303 // we convert captions except URL
304 if ( !strpos( $text, '://' ) ) {
305 $text = $this->translate( $text, $toVariant );
307 return " $title=\"$text\"";
311 * Dictionary-based conversion.
312 * This function would not parse the conversion rules.
313 * If you want to parse rules, try to use convert() or
316 * @param $text String: the text to be converted
317 * @param $toVariant String: the target language code
318 * @return String: the converted text
320 public function autoConvert( $text, $toVariant = false ) {
321 wfProfileIn( __METHOD__
);
326 $toVariant = $this->getPreferredVariant();
332 /* we convert everything except:
333 1. html markups (anything between < and >)
335 3. place holders created by the parser
338 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
339 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
344 // this one is needed when the text is inside an html markup
345 $htmlfix = '|<[^>]+$|^[^<>]*>';
347 // disable convert to variants between <code></code> tags
348 $codefix = '<code>.+?<\/code>|';
349 // disable convertsion of <script type="text/javascript"> ... </script>
350 $scriptfix = '<script.*?>.*?<\/script>|';
351 // disable conversion of <pre xxxx> ... </pre>
352 $prefix = '<pre.*?>.*?<\/pre>|';
354 $reg = '/' . $codefix . $scriptfix . $prefix .
355 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
357 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
359 $m = array_shift( $matches );
361 $ret = $this->translate( $m[0], $toVariant );
362 $mstart = $m[1] +
strlen( $m[0] );
364 // enable convertsion of '<img alt="xxxx" ... '
365 // or '<span title="xxxx" ... '
366 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
371 foreach ( $matches as $m ) {
372 $mark = substr( $text, $mstart, $m[1] - $mstart );
373 $mark = preg_replace_callback( $captionpattern,
374 array( &$this, 'captionConvert' ),
376 // Let's convert the trtext only once,
377 // it would give us more performance improvement
379 $trtext .= $m[0] . $trtextmark;
380 $mstart = $m[1] +
strlen( $m[0] );
383 $trtext = $this->translate( $trtext, $toVariant );
384 $trtext = StringUtils
::explode( $trtextmark, $trtext );
385 foreach ( $trtext as $t ) {
386 $ret .= array_shift( $notrtext );
389 wfProfileOut( __METHOD__
);
394 * Translate a string to a variant.
395 * Doesn't parse rules or do any of that other stuff, for that use
396 * convert() or convertTo().
398 * @param $text String: text to convert
399 * @param $variant String: variant language code
400 * @return String: translated text
402 protected function translate( $text, $variant ) {
403 wfProfileIn( __METHOD__
);
404 // If $text is empty or only includes spaces, do nothing
405 // Otherwise translate it
406 if ( trim( $text ) ) {
408 $text = $this->mTables
[$variant]->replace( $text );
410 wfProfileOut( __METHOD__
);
415 * Call translate() to convert text to all valid variants.
417 * @param $text String: the text to be converted
418 * @return Array: variant => converted text
420 public function autoConvertToAllVariants( $text ) {
421 wfProfileIn( __METHOD__
);
425 foreach ( $this->mVariants
as $variant ) {
426 $ret[$variant] = $this->translate( $text, $variant );
429 wfProfileOut( __METHOD__
);
434 * Convert link text to all valid variants.
435 * In the first, this function only convert text outside the
436 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
437 * titles, the text will get all converted always.
438 * So I removed this feature and deprecated the function.
440 * @param $text String: the text to be converted
441 * @return Array: variant => converted text
442 * @deprecated Use autoConvertToAllVariants() instead
444 public function convertLinkToAllVariants( $text ) {
445 return $this->autoConvertToAllVariants( $text );
449 * Apply manual conversion rules.
451 * @param $convRule Object: Object of ConverterRule
453 protected function applyManualConv( $convRule ) {
454 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
456 // Bug 24072: $mConvRuleTitle was overwritten by other manual
457 // rule(s) not for title, this breaks the title conversion.
458 $newConvRuleTitle = $convRule->getTitle();
459 if( $newConvRuleTitle ) {
460 // So I add an empty check for getTitle()
461 $this->mConvRuleTitle
= $newConvRuleTitle;
464 // merge/remove manual conversion rules to/from global table
465 $convTable = $convRule->getConvTable();
466 $action = $convRule->getRulesAction();
467 foreach ( $convTable as $variant => $pair ) {
468 if ( !$this->validateVariant( $variant ) ) {
472 if ( $action == 'add' ) {
473 foreach ( $pair as $from => $to ) {
474 // to ensure that $from and $to not be left blank
475 // so $this->translate() could always return a string
476 if ( $from ||
$to ) {
477 // more efficient than array_merge(), about 2.5 times.
478 $this->mTables
[$variant]->setPair( $from, $to );
481 } elseif ( $action == 'remove' ) {
482 $this->mTables
[$variant]->removeArray( $pair );
488 * Auto convert a Title object to a readable string in the
491 *@param $title Object: a object of Title
492 *@return String: converted title text
494 public function convertTitle( $title ) {
495 $variant = $this->getPreferredVariant();
496 $index = $title->getNamespace();
497 if ( $index === NS_MAIN
) {
500 // first let's check if a message has given us a converted name
501 $nsConvKey = 'conversion-ns' . $index;
502 if ( !wfEmptyMsg( $nsConvKey ) ) {
503 $text = wfMsgForContentNoTrans( $nsConvKey );
505 // the message does not exist, try retrieve it from the current
506 // variant's namespace names.
507 $langObj = $this->mLangObj
->factory( $variant );
508 $text = $langObj->getFormattedNsText( $index );
512 $text .= $title->getText();
513 $text = $this->translate( $text, $variant );
518 * Convert text to different variants of a language. The automatic
519 * conversion is done in autoConvert(). Here we parse the text
520 * marked with -{}-, which specifies special conversions of the
521 * text that can not be accomplished in autoConvert().
523 * Syntax of the markup:
524 * -{code1:text1;code2:text2;...}- or
525 * -{flags|code1:text1;code2:text2;...}- or
526 * -{text}- in which case no conversion should take place for text
528 * @param $text String: text to be converted
529 * @return String: converted text
531 public function convert( $text ) {
532 $variant = $this->getPreferredVariant();
533 return $this->convertTo( $text, $variant );
537 * Same as convert() except a extra parameter to custom variant.
539 * @param $text String: text to be converted
540 * @param $variant String: the target variant code
541 * @return String: converted text
543 public function convertTo( $text, $variant ) {
544 global $wgDisableLangConversion;
545 if ( $wgDisableLangConversion ) return $text;
546 return $this->recursiveConvertTopLevel( $text, $variant );
550 * Recursively convert text on the outside. Allow to use nested
551 * markups to custom rules.
553 * @param $text String: text to be converted
554 * @param $variant String: the target variant code
555 * @param $depth Integer: depth of recursion
556 * @return String: converted text
558 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
561 $length = strlen( $text );
562 while ( $startPos < $length ) {
564 $pos = strpos( $text, '-{', $startPos );
566 if ( $pos === false ) {
567 // No more markup, append final segment
568 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
574 // Append initial segment
575 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
580 // Do recursive conversion
581 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
588 * Recursively convert text on the inside.
590 * @param $text String: text to be converted
591 * @param $variant String: the target variant code
592 * @param $depth Integer: depth of recursion
593 * @return String: converted text
595 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
596 // Quick sanity check (no function calls)
597 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
598 throw new MWException( __METHOD__
.': invalid input string' );
603 $warningDone = false;
604 $length = strlen( $text );
606 while ( $startPos < $length ) {
608 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
618 // Append initial segment
619 $inner .= substr( $text, $startPos, $pos - $startPos );
627 if ( $depth >= $this->mMaxDepth
) {
629 if ( !$warningDone ) {
630 $inner .= '<span class="error">' .
631 wfMsgForContent( 'language-converter-depth-warning',
639 // Recursively parse another rule
640 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
645 $rule = new ConverterRule( $inner, $this );
646 $rule->parse( $variant );
647 $this->applyManualConv( $rule );
648 return $rule->getDisplay();
650 throw new MWException( __METHOD__
.': invalid regex match' );
655 if ( $startPos < $length ) {
656 $inner .= substr( $text, $startPos );
659 return '-{' . $this->autoConvert( $inner, $variant );
663 * If a language supports multiple variants, it is
664 * possible that non-existing link in one variant
665 * actually exists in another variant. This function
666 * tries to find it. See e.g. LanguageZh.php
668 * @param $link String: the name of the link
669 * @param $nt Mixed: the title object of the link
670 * @param $ignoreOtherCond Boolean: to disable other conditions when
671 * we need to transclude a template or update a category's link
672 * @return Null, the input parameters may be modified upon return
674 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
675 # If the article has already existed, there is no need to
676 # check it again, otherwise it may cause a fault.
677 if ( is_object( $nt ) && $nt->exists() ) {
681 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
683 $isredir = $wgRequest->getText( 'redirect', 'yes' );
684 $action = $wgRequest->getText( 'action' );
685 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
686 $disableLinkConversion = $wgDisableLangConversion
687 ||
$wgDisableTitleConversion;
688 $linkBatch = new LinkBatch();
692 if ( $disableLinkConversion ||
693 ( !$ignoreOtherCond &&
696 ||
$action == 'submit'
697 ||
$linkconvert == 'no'
698 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
702 if ( is_object( $nt ) ) {
703 $ns = $nt->getNamespace();
706 $variants = $this->autoConvertToAllVariants( $link );
707 if ( !$variants ) { // give up
713 foreach ( $variants as $v ) {
715 $varnt = Title
::newFromText( $v, $ns );
716 if ( !is_null( $varnt ) ) {
717 $linkBatch->addObj( $varnt );
723 // fetch all variants in single query
724 $linkBatch->execute();
726 foreach ( $titles as $varnt ) {
727 if ( $varnt->getArticleID() > 0 ) {
729 $link = $varnt->getText();
736 * Returns language specific hash options.
738 public function getExtraHashOptions() {
739 $variant = $this->getPreferredVariant();
740 return '!' . $variant ;
744 * Load default conversion tables.
745 * This method must be implemented in derived class.
749 function loadDefaultTables() {
750 $name = get_class( $this );
751 wfDie( "Must implement loadDefaultTables() method in class $name" );
755 * Load conversion tables either from the cache or the disk.
758 function loadTables( $fromcache = true ) {
759 if ( $this->mTablesLoaded
) {
763 wfProfileIn( __METHOD__
);
764 $this->mTablesLoaded
= true;
765 $this->mTables
= false;
767 wfProfileIn( __METHOD__
. '-cache' );
768 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
769 wfProfileOut( __METHOD__
. '-cache' );
772 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
773 wfProfileIn( __METHOD__
. '-recache' );
774 // not in cache, or we need a fresh reload.
775 // we will first load the default tables
776 // then update them using things in MediaWiki:Zhconversiontable/*
777 $this->loadDefaultTables();
778 foreach ( $this->mVariants
as $var ) {
779 $cached = $this->parseCachedTable( $var );
780 $this->mTables
[$var]->mergeArray( $cached );
783 $this->postLoadTables();
784 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
786 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
787 wfProfileOut( __METHOD__
. '-recache' );
789 wfProfileOut( __METHOD__
);
793 * Hook for post processig after conversion tables are loaded.
796 function postLoadTables() { }
799 * Reload the conversion tables.
803 function reloadTables() {
804 if ( $this->mTables
) {
805 unset( $this->mTables
);
807 $this->mTablesLoaded
= false;
808 $this->loadTables( false );
813 * Parse the conversion table stored in the cache.
815 * The tables should be in blocks of the following form:
822 * To make the tables more manageable, subpages are allowed
823 * and will be parsed recursively if $recursive == true.
826 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
827 global $wgMessageCache;
828 static $parsed = array();
830 if ( !is_object( $wgMessageCache ) ) {
834 $key = 'Conversiontable/' . $code;
836 $key .= '/' . $subpage;
838 if ( array_key_exists( $key, $parsed ) ) {
842 if ( strpos( $code, '/' ) === false ) {
843 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
844 if( $txt === false ){
845 # FIXME: this method doesn't seem to be expecting
846 # this possible outcome...
847 $txt = '<Conversiontable>';
850 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
851 "Conversiontable/$code" );
852 if ( $title && $title->exists() ) {
853 $article = new Article( $title );
854 $txt = $article->getContents();
860 // get all subpage links of the form
861 // [[MediaWiki:conversiontable/zh-xx/...|...]]
862 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
864 $subs = StringUtils
::explode( '[[', $txt );
866 foreach ( $subs as $sub ) {
867 $link = explode( ']]', $sub, 2 );
868 if ( count( $link ) != 2 ) {
871 $b = explode( '|', $link[0], 2 );
872 $b = explode( '/', trim( $b[0] ), 3 );
873 if ( count( $b ) == 3 ) {
879 if ( $b[0] == $linkhead && $b[1] == $code ) {
880 $sublinks[] = $sublink;
885 // parse the mappings in this page
886 $blocks = StringUtils
::explode( '-{', $txt );
889 foreach ( $blocks as $block ) {
891 // Skip the part before the first -{
895 $mappings = explode( '}-', $block, 2 );
896 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
898 $table = StringUtils
::explode( ';', $stripped );
899 foreach ( $table as $t ) {
900 $m = explode( '=>', $t, 3 );
901 if ( count( $m ) != 2 )
903 // trim any trailling comments starting with '//'
904 $tt = explode( '//', $m[1], 2 );
905 $ret[trim( $m[0] )] = trim( $tt[0] );
908 $parsed[$key] = true;
911 // recursively parse the subpages
913 foreach ( $sublinks as $link ) {
914 $s = $this->parseCachedTable( $code, $link, $recursive );
915 $ret = array_merge( $ret, $s );
919 if ( $this->mUcfirst
) {
920 foreach ( $ret as $k => $v ) {
921 $ret[Language
::ucfirst( $k )] = Language
::ucfirst( $v );
928 * Enclose a string with the "no conversion" tag. This is used by
929 * various functions in the Parser.
931 * @param $text String: text to be tagged for no conversion
932 * @param $noParse Unused (?)
933 * @return String: the tagged text
935 public function markNoConversion( $text, $noParse = false ) {
936 # don't mark if already marked
937 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
941 $ret = "-{R|$text}-";
946 * Convert the sorting key for category links. This should make different
947 * keys that are variants of each other map to the same key.
949 function convertCategoryKey( $key ) {
954 * Hook to refresh the cache of conversion tables when
955 * MediaWiki:conversiontable* is updated.
958 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
959 $iswatch, $section, $flags, $revision ) {
960 $titleobj = $article->getTitle();
961 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
962 $title = $titleobj->getDBkey();
963 $t = explode( '/', $title, 3 );
965 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
966 if ( $this->validateVariant( $t[1] ) ) {
967 $this->reloadTables();
975 * Armour rendered math against conversion.
976 * Wrap math into rawoutput -{R| math }- syntax.
978 public function armourMath( $text ) {
979 // we need to convert '-{' and '}-' to '-{' and '}-'
980 // to avoid a unwanted '}-' appeared after the math-image.
981 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
982 $ret = "-{R|$text}-";
987 * Get the cached separator pattern for ConverterRule::parseRules()
989 function getVarSeparatorPattern() {
990 if ( is_null( $this->mVarSeparatorPattern
) ) {
991 // varsep_pattern for preg_split:
992 // text should be splited by ";" only if a valid variant
993 // name exist after the markup, for example:
994 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
995 // <span style="font-size:120%;">yyy</span>;}-
996 // we should split it as:
998 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
999 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1003 foreach ( $this->mVariants
as $variant ) {
1004 // zh-hans:xxx;zh-hant:yyy
1005 $pat .= $variant . '\s*:|';
1006 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1007 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1010 $this->mVarSeparatorPattern
= $pat;
1012 return $this->mVarSeparatorPattern
;
1017 * Parser for rules of language conversion , parse rules in -{ }- tag.
1019 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1021 class ConverterRule
{
1022 var $mText; // original text in -{text}-
1023 var $mConverter; // LanguageConverter object
1024 var $mManualCodeError = '<strong class="error">code error!</strong>';
1025 var $mRuleDisplay = '';
1026 var $mRuleTitle = false;
1027 var $mRules = '';// string : the text of the rules
1028 var $mRulesAction = 'none';
1029 var $mFlags = array();
1030 var $mVariantFlags = array();
1031 var $mConvTable = array();
1032 var $mBidtable = array();// array of the translation in each variant
1033 var $mUnidtable = array();// array of the translation in each variant
1038 * @param $text String: the text between -{ and }-
1039 * @param $converter LanguageConverter object
1041 public function __construct( $text, $converter ) {
1042 $this->mText
= $text;
1043 $this->mConverter
= $converter;
1047 * Check if variants array in convert array.
1049 * @param $variants Array or string: variant language code
1050 * @return String: translated text
1052 public function getTextInBidtable( $variants ) {
1053 $variants = (array)$variants;
1057 foreach ( $variants as $variant ) {
1058 if ( isset( $this->mBidtable
[$variant] ) ) {
1059 return $this->mBidtable
[$variant];
1066 * Parse flags with syntax -{FLAG| ... }-
1069 function parseFlags() {
1070 $text = $this->mText
;
1072 $variantFlags = array();
1074 $sepPos = strpos( $text, '|' );
1075 if ( $sepPos !== false ) {
1076 $validFlags = $this->mConverter
->mFlags
;
1077 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1078 foreach ( $f as $ff ) {
1080 if ( isset( $validFlags[$ff] ) ) {
1081 $flags[$validFlags[$ff]] = true;
1084 $text = strval( substr( $text, $sepPos +
1 ) );
1089 } elseif ( isset( $flags['R'] ) ) {
1090 $flags = array( 'R' => true );// remove other flags
1091 } elseif ( isset( $flags['N'] ) ) {
1092 $flags = array( 'N' => true );// remove other flags
1093 } elseif ( isset( $flags['-'] ) ) {
1094 $flags = array( '-' => true );// remove other flags
1095 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1097 } elseif ( isset( $flags['H'] ) ) {
1098 // replace A flag, and remove other flags except T
1099 $temp = array( '+' => true, 'H' => true );
1100 if ( isset( $flags['T'] ) ) {
1103 if ( isset( $flags['D'] ) ) {
1108 if ( isset( $flags['A'] ) ) {
1112 if ( isset( $flags['D'] ) ) {
1113 unset( $flags['S'] );
1115 // try to find flags like "zh-hans", "zh-hant"
1116 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1117 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1118 if ( $variantFlags ) {
1119 $variantFlags = array_flip( $variantFlags );
1123 $this->mVariantFlags
= $variantFlags;
1124 $this->mRules
= $text;
1125 $this->mFlags
= $flags;
1129 * Generate conversion table.
1132 function parseRules() {
1133 $rules = $this->mRules
;
1134 $flags = $this->mFlags
;
1135 $bidtable = array();
1136 $unidtable = array();
1137 $variants = $this->mConverter
->mVariants
;
1138 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1140 $choice = preg_split( $varsep_pattern, $rules );
1142 foreach ( $choice as $c ) {
1143 $v = explode( ':', $c, 2 );
1144 if ( count( $v ) != 2 ) {
1145 // syntax error, skip
1148 $to = trim( $v[1] );
1150 $u = explode( '=>', $v, 2 );
1151 // if $to is empty, strtr() could return a wrong result
1152 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1153 $bidtable[$v] = $to;
1154 } elseif ( count( $u ) == 2 ) {
1155 $from = trim( $u[0] );
1157 if ( array_key_exists( $v, $unidtable )
1158 && !is_array( $unidtable[$v] )
1160 && in_array( $v, $variants ) ) {
1161 $unidtable[$v] = array( $from => $to );
1162 } elseif ( $to && in_array( $v, $variants ) ) {
1163 $unidtable[$v][$from] = $to;
1166 // syntax error, pass
1167 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1168 $bidtable = array();
1169 $unidtable = array();
1173 $this->mBidtable
= $bidtable;
1174 $this->mUnidtable
= $unidtable;
1180 function getRulesDesc() {
1181 $codesep = $this->mConverter
->mDescCodeSep
;
1182 $varsep = $this->mConverter
->mDescVarSep
;
1184 foreach ( $this->mBidtable
as $k => $v ) {
1185 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1187 foreach ( $this->mUnidtable
as $k => $a ) {
1188 foreach ( $a as $from => $to ) {
1189 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1190 "$codesep$to$varsep";
1197 * Parse rules conversion.
1200 function getRuleConvertedStr( $variant ) {
1201 $bidtable = $this->mBidtable
;
1202 $unidtable = $this->mUnidtable
;
1204 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1205 return $this->mRules
;
1207 // display current variant in bidirectional array
1208 $disp = $this->getTextInBidtable( $variant );
1209 // or display current variant in fallbacks
1211 $disp = $this->getTextInBidtable(
1212 $this->mConverter
->getVariantFallbacks( $variant ) );
1214 // or display current variant in unidirectional array
1215 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1216 $disp = array_values( $unidtable[$variant] );
1219 // or display frist text under disable manual convert
1221 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1222 if ( count( $bidtable ) > 0 ) {
1223 $disp = array_values( $bidtable );
1226 $disp = array_values( $unidtable );
1227 $disp = array_values( $disp[0] );
1236 * Generate conversion table for all text.
1239 function generateConvTable() {
1240 // Special case optimisation
1241 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1242 $this->mConvTable
= array();
1246 $bidtable = $this->mBidtable
;
1247 $unidtable = $this->mUnidtable
;
1248 $manLevel = $this->mConverter
->mManualLevel
;
1251 foreach ( $this->mConverter
->mVariants
as $v ) {
1252 /* for bidirectional array
1253 fill in the missing variants, if any,
1255 if ( !isset( $bidtable[$v] ) ) {
1257 $this->mConverter
->getVariantFallbacks( $v );
1258 $vf = $this->getTextInBidtable( $variantFallbacks );
1260 $bidtable[$v] = $vf;
1264 if ( isset( $bidtable[$v] ) ) {
1265 foreach ( $vmarked as $vo ) {
1266 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1267 // or -{H|zh:WordZh;zh-tw:WordTw}-
1268 // or -{-|zh:WordZh;zh-tw:WordTw}-
1269 // to introduce a custom mapping between
1270 // words WordZh and WordTw in the whole text
1271 if ( $manLevel[$v] == 'bidirectional' ) {
1272 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1274 if ( $manLevel[$vo] == 'bidirectional' ) {
1275 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1280 /*for unidirectional array fill to convert tables */
1281 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1282 && isset( $unidtable[$v] ) )
1284 if ( isset( $this->mConvTable
[$v] ) ) {
1285 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1287 $this->mConvTable
[$v] = $unidtable[$v];
1294 * Parse rules and flags.
1297 function parse( $variant = NULL ) {
1299 $variant = $this->mConverter
->getPreferredVariant();
1302 $variants = $this->mConverter
->mVariants
;
1303 $this->parseFlags();
1304 $flags = $this->mFlags
;
1306 // convert to specified variant
1307 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1308 if ( $this->mVariantFlags
) {
1309 // check if current variant in flags
1310 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1311 // then convert <text to convert> to current language
1312 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1314 } else { // if current variant no in flags,
1315 // then we check its fallback variants.
1317 $this->mConverter
->getVariantFallbacks( $variant );
1318 foreach ( $variantFallbacks as $variantFallback ) {
1319 // if current variant's fallback exist in flags
1320 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1321 // then convert <text to convert> to fallback language
1323 $this->mConverter
->autoConvert( $this->mRules
,
1329 $this->mFlags
= $flags = array( 'R' => true );
1332 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1333 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1334 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1335 $this->parseRules();
1337 $rules = $this->mRules
;
1339 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1340 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1341 // fill all variants if text in -{A/H/-|text} without rules
1342 foreach ( $this->mConverter
->mVariants
as $v ) {
1343 $this->mBidtable
[$v] = $rules;
1345 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1346 $this->mFlags
= $flags = array( 'R' => true );
1350 $this->mRuleDisplay
= false;
1351 foreach ( $flags as $flag => $unused ) {
1354 // if we don't do content convert, still strip the -{}- tags
1355 $this->mRuleDisplay
= $rules;
1358 // process N flag: output current variant name
1359 $ruleVar = trim( $rules );
1360 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1361 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1363 $this->mRuleDisplay
= '';
1367 // process D flag: output rules description
1368 $this->mRuleDisplay
= $this->getRulesDesc();
1371 // process H,- flag or T only: output nothing
1372 $this->mRuleDisplay
= '';
1375 $this->mRulesAction
= 'remove';
1376 $this->mRuleDisplay
= '';
1379 $this->mRulesAction
= 'add';
1380 $this->mRuleDisplay
= '';
1383 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1386 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1387 $this->mRuleDisplay
= '';
1390 // ignore unknown flags (but see error case below)
1393 if ( $this->mRuleDisplay
=== false ) {
1394 $this->mRuleDisplay
= $this->mManualCodeError
;
1397 $this->generateConvTable();
1403 function hasRules() {
1408 * Get display text on markup -{...}-
1411 function getDisplay() {
1412 return $this->mRuleDisplay
;
1416 * Get converted title.
1419 function getTitle() {
1420 return $this->mRuleTitle
;
1424 * Return how deal with conversion rules.
1427 function getRulesAction() {
1428 return $this->mRulesAction
;
1432 * Get conversion table. ( bidirectional and unidirectional
1433 * conversion table )
1436 function getConvTable() {
1437 return $this->mConvTable
;
1441 * Get conversion rules string.
1444 function getRules() {
1445 return $this->mRules
;
1449 * Get conversion flags.
1452 function getFlags() {
1453 return $this->mFlags
;