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 $mPreferredVariant = ''; // The User's preferred variant
20 var $mMainLanguageCode;
21 var $mVariants, $mVariantFallbacks, $mVariantNames;
22 var $mTablesLoaded = false;
24 var $mNamespaceTables;
25 var $mDoTitleConvert = true, $mDoContentConvert = true;
26 // 'bidirectional' 'unidirectional' 'disable' for each variant
28 var $mTitleFromFlag = false;
33 var $mDescCodeSep = ':', $mDescVarSep = ';';
34 var $mUcfirst = false;
35 var $mTitleOriginal = '';
36 var $mTitleDisplay = '';
37 var $mHeaderVariant = null;
39 const CACHE_VERSION_KEY
= 'VERSION 6';
44 * @param $langobj The Language Object
45 * @param string $maincode the main language code of this language
46 * @param array $variants the supported variants of this language
47 * @param array $variantfallback the fallback language of each variant
48 * @param array $markup array defining the markup used for manual conversion
49 * @param array $flags array defining the custom strings that maps to the
51 * @param array $manualLevel limit for supported variants
54 function __construct( $langobj, $maincode,
56 $variantfallbacks = array(),
59 $manualLevel = array() ) {
60 $this->mLangObj
= $langobj;
61 $this->mMainLanguageCode
= $maincode;
63 global $wgDisabledVariants;
64 $this->mVariants
= array();
65 foreach ( $variants as $variant ) {
66 if ( !in_array( $variant, $wgDisabledVariants ) ) {
67 $this->mVariants
[] = $variant;
70 $this->mVariantFallbacks
= $variantfallbacks;
71 global $wgLanguageNames;
72 $this->mVariantNames
= $wgLanguageNames;
73 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
77 'unidsep' => '=>', // for unidirectional conversion
82 $this->mMarkup
= array_merge( $m, $markup );
84 // 'S' show converted text
85 // '+' add rules for alltext
86 // 'E' the gave flags is error
87 // these flags above are reserved for program
88 'A' => 'A', // add rule for convert code (all text convert)
89 'T' => 'T', // title convert
90 'R' => 'R', // raw content
91 'D' => 'D', // convert description (subclass implement)
92 '-' => '-', // remove convert (not implement)
93 'H' => 'H', // add rule for convert code
94 // (but no display in placed code )
95 'N' => 'N' // current variant name
97 $this->mFlags
= array_merge( $f, $flags );
98 foreach ( $this->mVariants
as $v ) {
99 if ( array_key_exists( $v, $manualLevel ) ) {
100 $this->mManualLevel
[$v] = $manualLevel[$v];
102 $this->mManualLevel
[$v] = 'bidirectional';
104 $this->mNamespaceTables
[$v] = array();
105 $this->mFlags
[$v] = $v;
112 function getVariants() {
113 return $this->mVariants
;
117 * In case some variant is not defined in the markup, we need
118 * to have some fallback. For example, in zh, normally people
119 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
120 * when zh-sg is preferred but not defined, we will pick zh-hans
121 * in this case. Right now this is only used by zh.
123 * @param string $v The language code of the variant
124 * @return string array The code of the fallback language or false if there
128 function getVariantFallbacks( $v ) {
129 if ( isset( $this->mVariantFallbacks
[$v] ) ) {
130 return $this->mVariantFallbacks
[$v];
132 return $this->mMainLanguageCode
;
136 * Get preferred language variants.
137 * @param boolean $fromUser Get it from $wgUser's preferences
138 * @param boolean $fromHeader Get it from Accept-Language
139 * @return string the preferred language code
142 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
143 global $wgUser, $wgRequest, $wgVariantArticlePath,
144 $wgDefaultLanguageVariant, $wgOut;
146 // see if the preference is set in the request
147 $req = $wgRequest->getText( 'variant' );
148 if ( in_array( $req, $this->mVariants
) ) {
149 $this->mPreferredVariant
= $req;
150 return $this->mPreferredVariant
;
154 // bug 21974, don't return $this->mPreferredVariant if
156 if ( $this->mPreferredVariant
) {
157 return $this->mPreferredVariant
;
160 // figure out user lang without constructing wgLang to avoid
161 // infinite recursion
162 $defaultUserLang = $wgUser->getOption( 'language' );
164 // get language variant preference from logged in users
165 // Don't call this on stub objects because that causes infinite
166 // recursion during initialisation
167 if ( $wgUser->isLoggedIn() ) {
168 $this->mPreferredVariant
= $wgUser->getOption( 'variant' );
172 $defaultUserLang = $this->mMainLanguageCode
;
174 $userLang = $wgRequest->getVal( 'uselang', $defaultUserLang );
176 // see if interface language is same as content, if not, prevent
178 if ( ! in_array( $userLang, $this->mVariants
) ) {
180 $this->mPreferredVariant
= $this->mMainLanguageCode
;
181 return $this->mPreferredVariant
;
182 } elseif ( $this->mPreferredVariant
) {
183 // if the variant was set above and it iss a variant of
184 // the content language
185 return $this->mPreferredVariant
;
188 // see if default variant is globaly set
189 if ( $wgDefaultLanguageVariant != false
190 && in_array( $wgDefaultLanguageVariant, $this->mVariants
) ) {
191 $this->mPreferredVariant
= $wgDefaultLanguageVariant;
192 return $this->mPreferredVariant
;
195 $headerVariant = $this->getHeaderVariant();
196 if ( $fromHeader && $headerVariant ) {
197 return $headerVariant;
200 return $this->mMainLanguageCode
;
204 * Determine the language variant from the Accept-Language header.
206 * @returns mixed variant if one found, false otherwise.
208 function getHeaderVariant() {
211 if ( $this->mHeaderVariant
) {
212 return $this->mHeaderVariant
;
215 // see if some supported language variant is set in the
216 // http header, but we don't set the mPreferredVariant
217 // variable in case this is called before the user's
218 // preference is loaded
220 $acceptLanguage = $wgRequest->getHeader( 'Accept-Language' );
221 if ( !$acceptLanguage ) {
226 $result = explode( ',', strtolower( $acceptLanguage ) );
228 $languages = array();
230 foreach ( $result as $elem ) {
231 // if $elem likes 'zh-cn;q=0.9'
232 if ( ( $posi = strpos( $elem, ';' ) ) !== false ) {
233 // get the real language code likes 'zh-cn'
234 $languages[] = substr( $elem, 0, $posi );
236 $languages[] = $elem;
240 $fallback_languages = array();
241 foreach ( $languages as $language ) {
243 $language = trim( $language );
244 if ( in_array( $language, $this->mVariants
) ) {
245 $this->mHeaderVariant
= $language;
248 // To see if there are fallbacks of current language.
249 // We record these fallback variants, and process
251 $fallbacks = $this->getVariantFallbacks( $language );
252 if ( is_string( $fallbacks ) ) {
253 $fallback_languages[] = $fallbacks;
254 } elseif ( is_array( $fallbacks ) ) {
255 $fallback_languages =
256 array_merge( $fallback_languages,
262 // process fallback languages now
263 $fallback_languages = array_unique( $fallback_languages );
264 foreach ( $fallback_languages as $language ) {
265 if ( in_array( $language, $this->mVariants
) ) {
266 $this->mHeaderVariant
= $language;
273 * Caption convert, base on preg_replace_callback.
275 * To convert text in "title" or "alt", like '<img alt="text" ... '
276 * or '<span title="text" ... '
278 * @return string like ' alt="yyyy"' or ' title="yyyy"'
281 function captionConvert( $matches ) {
282 $toVariant = $this->getPreferredVariant();
283 $title = $matches[1];
285 // we convert captions except URL
286 if ( !strpos( $text, '://' ) ) {
287 $text = $this->translate( $text, $toVariant );
289 return " $title=\"$text\"";
293 * Dictionary-based conversion.
295 * @param string $text the text to be converted
296 * @param string $toVariant the target language code
297 * @return string the converted text
300 function autoConvert( $text, $toVariant = false ) {
301 $fname = 'LanguageConverter::autoConvert';
303 wfProfileIn( $fname );
305 if ( !$this->mTablesLoaded
) {
310 $toVariant = $this->getPreferredVariant();
312 if ( !in_array( $toVariant, $this->mVariants
) ) {
316 /* we convert everything except:
317 1. html markups (anything between < and >)
319 3. place holders created by the parser
322 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
323 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
328 // this one is needed when the text is inside an html markup
329 $htmlfix = '|<[^>]+$|^[^<>]*>';
331 // disable convert to variants between <code></code> tags
332 $codefix = '<code>.+?<\/code>|';
333 // disable convertsion of <script type="text/javascript"> ... </script>
334 $scriptfix = '<script.*?>.*?<\/script>|';
335 // disable conversion of <pre xxxx> ... </pre>
336 $prefix = '<pre.*?>.*?<\/pre>|';
338 $reg = '/' . $codefix . $scriptfix . $prefix .
339 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
341 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
343 $m = array_shift( $matches );
345 $ret = $this->translate( $m[0], $toVariant );
346 $mstart = $m[1] +
strlen( $m[0] );
348 // enable convertsion of '<img alt="xxxx" ... '
349 // or '<span title="xxxx" ... '
350 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
355 foreach ( $matches as $m ) {
356 $mark = substr( $text, $mstart, $m[1] - $mstart );
357 $mark = preg_replace_callback( $captionpattern,
358 array( &$this, 'captionConvert' ),
360 // Let's convert the trtext only once,
361 // it would give us more performance improvement
363 $trtext .= $m[0] . $trtextmark;
364 $mstart = $m[1] +
strlen( $m[0] );
367 $trtext = $this->translate( $trtext, $toVariant );
368 $trtext = StringUtils
::explode( $trtextmark, $trtext );
369 foreach ( $trtext as $t ) {
370 $ret .= array_shift( $notrtext );
373 wfProfileOut( $fname );
378 * Translate a string to a variant.
379 * Doesn't process markup or do any of that other stuff, for that use
382 * @param string $text Text to convert
383 * @param string $variant Variant language code
384 * @return string Translated text
387 function translate( $text, $variant ) {
388 wfProfileIn( __METHOD__
);
389 // If $text is empty or only includes spaces, do nothing
390 // Otherwise translate it
391 if ( trim( $text ) ) {
392 if ( !$this->mTablesLoaded
) {
395 $text = $this->mTables
[$variant]->replace( $text );
397 wfProfileOut( __METHOD__
);
402 * Convert text to all supported variants.
404 * @param string $text the text to be converted
405 * @return array of string
408 function autoConvertToAllVariants( $text ) {
409 $fname = 'LanguageConverter::autoConvertToAllVariants';
410 wfProfileIn( $fname );
411 if ( !$this->mTablesLoaded
) {
416 foreach ( $this->mVariants
as $variant ) {
417 $ret[$variant] = $this->translate( $text, $variant );
420 wfProfileOut( $fname );
425 * Convert link text to all supported variants.
427 * @param string $text the text to be converted
428 * @return array of string
431 function convertLinkToAllVariants( $text ) {
432 if ( !$this->mTablesLoaded
) {
437 $tarray = explode( $this->mMarkup
['begin'], $text );
438 $tfirst = array_shift( $tarray );
440 foreach ( $this->mVariants
as $variant ) {
441 $ret[$variant] = $this->translate( $tfirst, $variant );
444 foreach ( $tarray as $txt ) {
445 $marked = explode( $this->mMarkup
['end'], $txt, 2 );
447 foreach ( $this->mVariants
as $variant ) {
448 $ret[$variant] .= $this->mMarkup
['begin'] . $marked[0] .
449 $this->mMarkup
['end'];
450 if ( array_key_exists( 1, $marked ) ) {
451 $ret[$variant] .= $this->translate( $marked[1], $variant );
461 * Prepare manual conversion table.
464 function applyManualConv( $convRule ) {
465 // use syntax -{T|zh:TitleZh;zh-tw:TitleTw}- for custom
466 // conversion in title
467 $title = $convRule->getTitle();
469 $this->mTitleFromFlag
= true;
470 $this->mTitleDisplay
= $title;
473 // apply manual conversion table to global table
474 $convTable = $convRule->getConvTable();
475 $action = $convRule->getRulesAction();
476 foreach ( $convTable as $variant => $pair ) {
477 if ( !in_array( $variant, $this->mVariants
) ) {
481 if ( $action == 'add' ) {
482 foreach ( $pair as $from => $to ) {
483 // to ensure that $from and $to not be left blank
484 // so $this->translate() could always return a string
485 if ( $from ||
$to ) {
486 // more efficient than array_merge(), about 2.5 times.
487 $this->mTables
[$variant]->setPair( $from, $to );
490 } elseif ( $action == 'remove' ) {
491 $this->mTables
[$variant]->removeArray( $pair );
497 * Convert text using a parser object for context.
500 function parserConvert( $text, &$parser ) {
501 global $wgDisableLangConversion;
502 /* don't do anything if this is the conversion table */
503 if ( $parser->getTitle()->getNamespace() == NS_MEDIAWIKI
504 && strpos( $parser->mTitle
->getText(),
505 'Conversiontable' ) !== false ) {
509 if ( $wgDisableLangConversion ) {
513 $text = $this->convert( $text );
515 $this->convertTitle();
516 $parser->mOutput
->setTitleText( $this->mTitleDisplay
);
523 * @param string $title the title included namespace
524 * @return array of string
527 function convertNamespace( $title, $variant ) {
528 $splittitle = explode( ':', $title );
529 if ( count( $splittitle ) < 2 ) {
532 if ( isset( $this->mNamespaceTables
[$variant][$splittitle[0]] ) ) {
533 $splittitle[0] = $this->mNamespaceTables
[$variant][$splittitle[0]];
535 $ret = implode( ':', $splittitle );
540 * Pre convert title. Store the original title $this->mTitleOrginal;
541 * store the default converted title to $this->mTitleDisplay.
544 function preConvertTitle( $text, $variant ) {
545 $this->mTitleOriginal
= $text;
547 $text = $this->convertNamespace( $text, $variant );
548 $this->mTitleDisplay
= $this->convert( $text );
555 function convertTitle() {
556 global $wgDisableTitleConversion, $wgUser, $wgRequest;
557 $isredir = $wgRequest->getText( 'redirect', 'yes' );
558 $action = $wgRequest->getText( 'action' );
559 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
561 // check for the global variable, __NOTC__ magic word, and user setting
562 if ( $wgDisableTitleConversion ||
!$this->mDoTitleConvert ||
563 $wgUser->getOption( 'noconvertlink' ) == 1 ) {
564 $this->mTitleDisplay
= $this->mTitleOriginal
;
565 } elseif ( $isredir == 'no'
567 ||
$linkconvert == 'no' ) {
568 // check for GET params
569 $this->mTitleDisplay
= $this->mTitleOriginal
;
574 * Convert text to different variants of a language. The automatic
575 * conversion is done in autoConvert(). Here we parse the text
576 * marked with -{}-, which specifies special conversions of the
577 * text that can not be accomplished in autoConvert().
579 * Syntax of the markup:
580 * -{code1:text1;code2:text2;...}- or
581 * -{flags|code1:text1;code2:text2;...}- or
582 * -{text}- in which case no conversion should take place for text
584 * @param string $text text to be converted
585 * @param bool $isTitle whether this conversion is for the article title
586 * @return string converted text
589 function convert( $text, $isTitle = false ) {
591 $mw =& MagicWord
::get( 'notitleconvert' );
592 if ( $mw->matchAndRemove( $text ) ) {
593 $this->mDoTitleConvert
= false;
595 $mw =& MagicWord
::get( 'nocontentconvert' );
596 if ( $mw->matchAndRemove( $text ) ) {
597 $this->mDoContentConvert
= false;
600 // no conversion if redirecting
601 $mw =& MagicWord
::get( 'redirect' );
602 if ( $mw->matchStart( $text ) ) {
606 $plang = $this->getPreferredVariant();
608 // for title convertion
610 $this->preConvertTitle( $text, $plang );
614 $tarray = StringUtils
::explode( $this->mMarkup
['end'], $text );
617 foreach ( $tarray as $txt ) {
619 $marked = explode( $this->mMarkup
['begin'], $txt, 2 );
621 if ( $this->mDoContentConvert
) {
622 // Bug 19620: should convert a string immediately after a
624 $text .= $this->autoConvert( $marked[0], $plang );
629 if ( array_key_exists( 1, $marked ) ) {
630 $crule = new ConverterRule( $marked[1], $this );
631 $crule->parse( $plang );
632 $text .= $crule->getDisplay();
633 $this->applyManualConv( $crule );
635 $text .= $this->mMarkup
['end'];
639 // Remove the last delimiter (wasn't real)
640 $text = substr( $text, 0, - strlen( $this->mMarkup
['end'] ) );
645 * If a language supports multiple variants, it is
646 * possible that non-existing link in one variant
647 * actually exists in another variant. This function
648 * tries to find it. See e.g. LanguageZh.php
650 * @param string $link the name of the link
651 * @param mixed $nt the title object of the link
652 * @param boolean $ignoreOtherCond: to disable other conditions when
653 * we need to transclude a template or update a category's link
654 * @return null the input parameters may be modified upon return
657 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
658 # If the article has already existed, there is no need to
659 # check it again, otherwise it may cause a fault.
660 if ( is_object( $nt ) && $nt->exists() ) {
664 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
666 $isredir = $wgRequest->getText( 'redirect', 'yes' );
667 $action = $wgRequest->getText( 'action' );
668 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
669 $disableLinkConversion = $wgDisableLangConversion
670 ||
$wgDisableTitleConversion;
671 $linkBatch = new LinkBatch();
675 if ( $disableLinkConversion ||
676 ( !$ignoreOtherCond &&
679 ||
$action == 'submit'
680 ||
$linkconvert == 'no'
681 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
685 if ( is_object( $nt ) ) {
686 $ns = $nt->getNamespace();
689 $variants = $this->autoConvertToAllVariants( $link );
690 if ( $variants == false ) { // give up
696 foreach ( $variants as $v ) {
698 $varnt = Title
::newFromText( $v, $ns );
699 if ( !is_null( $varnt ) ) {
700 $linkBatch->addObj( $varnt );
706 // fetch all variants in single query
707 $linkBatch->execute();
709 foreach ( $titles as $varnt ) {
710 if ( $varnt->getArticleID() > 0 ) {
712 $link = $varnt->getText();
719 * Returns language specific hash options.
723 function getExtraHashOptions() {
724 $variant = $this->getPreferredVariant();
725 return '!' . $variant ;
729 * Get title text as defined in the body of the article text.
733 function getParsedTitle() {
734 return $this->mTitleDisplay
;
738 * Load default conversion tables.
739 * This method must be implemented in derived class.
743 function loadDefaultTables() {
744 $name = get_class( $this );
745 wfDie( "Must implement loadDefaultTables() method in class $name" );
749 * Load conversion tables either from the cache or the disk.
752 function loadTables( $fromcache = true ) {
754 if ( $this->mTablesLoaded
) {
757 wfProfileIn( __METHOD__
);
758 $this->mTablesLoaded
= true;
759 $this->mTables
= false;
761 wfProfileIn( __METHOD__
. '-cache' );
762 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
763 wfProfileOut( __METHOD__
. '-cache' );
766 ||
!isset( $this->mTables
[self
::CACHE_VERSION_KEY
] ) ) {
767 wfProfileIn( __METHOD__
. '-recache' );
768 // not in cache, or we need a fresh reload.
769 // we will first load the default tables
770 // then update them using things in MediaWiki:Zhconversiontable/*
771 $this->loadDefaultTables();
772 foreach ( $this->mVariants
as $var ) {
773 $cached = $this->parseCachedTable( $var );
774 $this->mTables
[$var]->mergeArray( $cached );
777 $this->postLoadTables();
778 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
780 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
781 wfProfileOut( __METHOD__
. '-recache' );
783 wfProfileOut( __METHOD__
);
787 * Hook for post processig after conversion tables are loaded.
790 function postLoadTables() { }
793 * Reload the conversion tables.
797 function reloadTables() {
798 if ( $this->mTables
) {
799 unset( $this->mTables
);
801 $this->mTablesLoaded
= false;
802 $this->loadTables( false );
807 * Parse the conversion table stored in the cache.
809 * The tables should be in blocks of the following form:
816 * To make the tables more manageable, subpages are allowed
817 * and will be parsed recursively if $recursive == true.
820 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
821 global $wgMessageCache;
822 static $parsed = array();
824 if ( !is_object( $wgMessageCache ) ) {
828 $key = 'Conversiontable/' . $code;
830 $key .= '/' . $subpage;
832 if ( array_key_exists( $key, $parsed ) ) {
836 if ( strpos( $code, '/' ) === false ) {
837 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
839 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
840 "Conversiontable/$code" );
841 if ( $title && $title->exists() ) {
842 $article = new Article( $title );
843 $txt = $article->getContents();
849 // get all subpage links of the form
850 // [[MediaWiki:conversiontable/zh-xx/...|...]]
851 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
853 $subs = explode( '[[', $txt );
855 foreach ( $subs as $sub ) {
856 $link = explode( ']]', $sub, 2 );
857 if ( count( $link ) != 2 ) {
860 $b = explode( '|', $link[0] );
861 $b = explode( '/', trim( $b[0] ), 3 );
862 if ( count( $b ) == 3 ) {
868 if ( $b[0] == $linkhead && $b[1] == $code ) {
869 $sublinks[] = $sublink;
874 // parse the mappings in this page
875 $blocks = explode( $this->mMarkup
['begin'], $txt );
876 array_shift( $blocks );
878 foreach ( $blocks as $block ) {
879 $mappings = explode( $this->mMarkup
['end'], $block, 2 );
880 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
882 $table = explode( ';', $stripped );
883 foreach ( $table as $t ) {
884 $m = explode( '=>', $t );
885 if ( count( $m ) != 2 )
887 // trim any trailling comments starting with '//'
888 $tt = explode( '//', $m[1], 2 );
889 $ret[trim( $m[0] )] = trim( $tt[0] );
892 $parsed[$key] = true;
895 // recursively parse the subpages
897 foreach ( $sublinks as $link ) {
898 $s = $this->parseCachedTable( $code, $link, $recursive );
899 $ret = array_merge( $ret, $s );
903 if ( $this->mUcfirst
) {
904 foreach ( $ret as $k => $v ) {
905 $ret[Language
::ucfirst( $k )] = Language
::ucfirst( $v );
912 * Enclose a string with the "no conversion" tag. This is used by
913 * various functions in the Parser.
915 * @param string $text text to be tagged for no conversion
916 * @return string the tagged text
919 function markNoConversion( $text, $noParse = false ) {
920 # don't mark if already marked
921 if ( strpos( $text, $this->mMarkup
['begin'] )
922 ||
strpos( $text, $this->mMarkup
['end'] ) ) {
926 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
931 * Convert the sorting key for category links. This should make different
932 * keys that are variants of each other map to the same key.
934 function convertCategoryKey( $key ) {
939 * Hook to refresh the cache of conversion tables when
940 * MediaWiki:conversiontable* is updated.
943 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
944 $iswatch, $section, $flags, $revision ) {
945 $titleobj = $article->getTitle();
946 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
947 $title = $titleobj->getDBkey();
948 $t = explode( '/', $title, 3 );
950 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
951 if ( in_array( $t[1], $this->mVariants
) ) {
952 $this->reloadTables();
960 * Armour rendered math against conversion.
961 * Wrap math into rawoutput -{R| math }- syntax.
964 function armourMath( $text ) {
965 // we need to convert '-{' and '}-' to '-{' and '}-'
966 // to avoid a unwanted '}-' appeared after the math-image.
967 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
968 $ret = $this->mMarkup
['begin'] . 'R|' . $text . $this->mMarkup
['end'];
974 * Parser for rules of language conversion , parse rules in -{ }- tag.
976 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
978 class ConverterRule
{
979 var $mText; // original text in -{text}-
980 var $mConverter; // LanguageConverter object
981 var $mManualCodeError = '<strong class="error">code error!</strong>';
982 var $mRuleDisplay = '';
983 var $mRuleTitle = false;
984 var $mRules = '';// string : the text of the rules
985 var $mRulesAction = 'none';
986 var $mFlags = array();
987 var $mConvTable = array();
988 var $mBidtable = array();// array of the translation in each variant
989 var $mUnidtable = array();// array of the translation in each variant
994 * @param string $text the text between -{ and }-
995 * @param object $converter a LanguageConverter object
998 function __construct( $text, $converter ) {
999 $this->mText
= $text;
1000 $this->mConverter
= $converter;
1001 foreach ( $converter->mVariants
as $v ) {
1002 $this->mConvTable
[$v] = array();
1007 * Check if variants array in convert array.
1009 * @param string $variant Variant language code
1010 * @return string Translated text
1013 function getTextInBidtable( $variants ) {
1014 if ( is_string( $variants ) ) {
1015 $variants = array( $variants );
1017 if ( !is_array( $variants ) ) {
1020 foreach ( $variants as $variant ) {
1021 if ( array_key_exists( $variant, $this->mBidtable
) ) {
1022 return $this->mBidtable
[$variant];
1029 * Parse flags with syntax -{FLAG| ... }-
1032 function parseFlags() {
1033 $text = $this->mText
;
1034 if ( strlen( $text ) < 2 ) {
1035 $this->mFlags
= array( 'R' );
1036 $this->mRules
= $text;
1041 $markup = $this->mConverter
->mMarkup
;
1042 $validFlags = $this->mConverter
->mFlags
;
1043 $variants = $this->mConverter
->mVariants
;
1045 $tt = explode( $markup['flagsep'], $text, 2 );
1046 if ( count( $tt ) == 2 ) {
1047 $f = explode( $markup['varsep'], $tt[0] );
1048 foreach ( $f as $ff ) {
1050 if ( array_key_exists( $ff, $validFlags )
1051 && !in_array( $validFlags[$ff], $flags ) ) {
1052 $flags[] = $validFlags[$ff];
1061 if ( in_array( 'R', $flags ) ) {
1062 $flags = array( 'R' );// remove other flags
1063 } elseif ( in_array( 'N', $flags ) ) {
1064 $flags = array( 'N' );// remove other flags
1065 } elseif ( in_array( '-', $flags ) ) {
1066 $flags = array( '-' );// remove other flags
1067 } elseif ( count( $flags ) == 1 && $flags[0] == 'T' ) {
1069 } elseif ( in_array( 'H', $flags ) ) {
1070 // replace A flag, and remove other flags except T
1071 $temp = array( '+', 'H' );
1072 if ( in_array( 'T', $flags ) ) {
1075 if ( in_array( 'D', $flags ) ) {
1080 if ( in_array( 'A', $flags ) ) {
1084 if ( in_array( 'D', $flags ) ) {
1085 $flags = array_diff( $flags, array( 'S' ) );
1087 $flags_temp = array();
1088 foreach ( $variants as $variant ) {
1089 // try to find flags like "zh-hans", "zh-hant"
1090 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1091 if ( in_array( $variant, $flags ) )
1092 $flags_temp[] = $variant;
1094 if ( count( $flags_temp ) !== 0 ) {
1095 $flags = $flags_temp;
1098 if ( count( $flags ) == 0 ) {
1099 $flags = array( 'S' );
1101 $this->mRules
= $rules;
1102 $this->mFlags
= $flags;
1106 * Generate conversion table.
1109 function parseRules() {
1110 $rules = $this->mRules
;
1111 $flags = $this->mFlags
;
1112 $bidtable = array();
1113 $unidtable = array();
1114 $markup = $this->mConverter
->mMarkup
;
1115 $variants = $this->mConverter
->mVariants
;
1117 // varsep_pattern for preg_split:
1118 // text should be splited by ";" only if a valid variant
1119 // name exist after the markup, for example:
1120 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1121 // <span style="font-size:120%;">yyy</span>;}-
1122 // we should split it as:
1124 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1125 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1128 $varsep_pattern = '/' . $markup['varsep'] . '\s*' . '(?=';
1129 foreach ( $variants as $variant ) {
1130 // zh-hans:xxx;zh-hant:yyy
1131 $varsep_pattern .= $variant . '\s*' . $markup['codesep'] . '|';
1132 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1133 $varsep_pattern .= '[^;]*?' . $markup['unidsep'] . '\s*' . $variant
1134 . '\s*' . $markup['codesep'] . '|';
1136 $varsep_pattern .= '\s*$)/';
1138 $choice = preg_split( $varsep_pattern, $rules );
1140 foreach ( $choice as $c ) {
1141 $v = explode( $markup['codesep'], $c, 2 );
1142 if ( count( $v ) != 2 ) {
1143 // syntax error, skip
1146 $to = trim( $v[1] );
1148 $u = explode( $markup['unidsep'], $v, 2 );
1149 // if $to is empty, strtr() could return a wrong result
1150 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1151 $bidtable[$v] = $to;
1152 } elseif ( count( $u ) == 2 ) {
1153 $from = trim( $u[0] );
1155 if ( array_key_exists( $v, $unidtable )
1156 && !is_array( $unidtable[$v] )
1158 && in_array( $v, $variants ) ) {
1159 $unidtable[$v] = array( $from => $to );
1160 } elseif ( $to && in_array( $v, $variants ) ) {
1161 $unidtable[$v][$from] = $to;
1164 // syntax error, pass
1165 if ( !array_key_exists( $v, $this->mConverter
->mVariantNames
) ) {
1166 $bidtable = array();
1167 $unidtable = array();
1171 $this->mBidtable
= $bidtable;
1172 $this->mUnidtable
= $unidtable;
1178 function getRulesDesc() {
1179 $codesep = $this->mConverter
->mDescCodeSep
;
1180 $varsep = $this->mConverter
->mDescVarSep
;
1182 foreach ( $this->mBidtable
as $k => $v ) {
1183 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1185 foreach ( $this->mUnidtable
as $k => $a ) {
1186 foreach ( $a as $from => $to ) {
1187 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1188 "$codesep$to$varsep";
1195 * Parse rules conversion.
1198 function getRuleConvertedStr( $variant, $doConvert ) {
1199 $bidtable = $this->mBidtable
;
1200 $unidtable = $this->mUnidtable
;
1202 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1203 return $this->mRules
;
1204 } elseif ( $doConvert ) { // the text converted
1205 // display current variant in bidirectional array
1206 $disp = $this->getTextInBidtable( $variant );
1207 // or display current variant in fallbacks
1209 $disp = $this->getTextInBidtable(
1210 $this->mConverter
->getVariantFallbacks( $variant ) );
1212 // or display current variant in unidirectional array
1213 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1214 $disp = array_values( $unidtable[$variant] );
1217 // or display frist text under disable manual convert
1219 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1220 if ( count( $bidtable ) > 0 ) {
1221 $disp = array_values( $bidtable );
1224 $disp = array_values( $unidtable );
1225 $disp = array_values( $disp[0] );
1230 } else { // no convert
1231 return $this->mRules
;
1236 * Generate conversion table for all text.
1239 function generateConvTable() {
1240 $flags = $this->mFlags
;
1241 $bidtable = $this->mBidtable
;
1242 $unidtable = $this->mUnidtable
;
1243 $manLevel = $this->mConverter
->mManualLevel
;
1246 foreach ( $this->mConverter
->mVariants
as $v ) {
1247 /* for bidirectional array
1248 fill in the missing variants, if any,
1250 if ( !array_key_exists( $v, $bidtable ) ) {
1252 $this->mConverter
->getVariantFallbacks( $v );
1253 $vf = $this->getTextInBidtable( $variantFallbacks );
1255 $bidtable[$v] = $vf;
1259 if ( array_key_exists( $v, $bidtable ) ) {
1260 foreach ( $vmarked as $vo ) {
1261 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1262 // or -{H|zh:WordZh;zh-tw:WordTw}-
1263 // or -{-|zh:WordZh;zh-tw:WordTw}-
1264 // to introduce a custom mapping between
1265 // words WordZh and WordTw in the whole text
1266 if ( $manLevel[$v] == 'bidirectional' ) {
1267 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1269 if ( $manLevel[$vo] == 'bidirectional' ) {
1270 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1275 /*for unidirectional array fill to convert tables */
1276 if ( ( $manLevel[$v] == 'bidirectional'
1277 ||
$manLevel[$v] == 'unidirectional' )
1278 && array_key_exists( $v, $unidtable ) ) {
1279 $ct = $this->mConvTable
[$v];
1280 $this->mConvTable
[$v] = array_merge( $ct, $unidtable[$v] );
1286 * Parse rules and flags.
1289 function parse( $variant = NULL ) {
1291 $variant = $this->mConverter
->getPreferredVariant();
1294 $variants = $this->mConverter
->mVariants
;
1295 $this->parseFlags();
1296 $flags = $this->mFlags
;
1298 // convert to specified variant
1299 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1300 if ( count( array_diff( $flags, $variants ) ) == 0
1301 and count( $flags ) != 0 ) {
1302 // check if current variant in flags
1303 if ( in_array( $variant, $flags ) ) {
1304 // then convert <text to convert> to current language
1305 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1307 } else { // if current variant no in flags,
1308 // then we check its fallback variants.
1310 $this->mConverter
->getVariantFallbacks( $variant );
1311 foreach ( $variantFallbacks as $variantFallback ) {
1312 // if current variant's fallback exist in flags
1313 if ( in_array( $variantFallback, $flags ) ) {
1314 // then convert <text to convert> to fallback language
1316 $this->mConverter
->autoConvert( $this->mRules
,
1322 $this->mFlags
= $flags = array( 'R' );
1325 if ( !in_array( 'R', $flags ) ||
!in_array( 'N', $flags ) ) {
1326 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1327 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1329 $this->parseRules();
1331 $rules = $this->mRules
;
1333 if ( count( $this->mBidtable
) == 0
1334 && count( $this->mUnidtable
) == 0 ) {
1335 if ( in_array( '+', $flags ) ||
in_array( '-', $flags ) ) {
1336 // fill all variants if text in -{A/H/-|text} without rules
1337 foreach ( $this->mConverter
->mVariants
as $v ) {
1338 $this->mBidtable
[$v] = $rules;
1340 } elseif ( !in_array( 'N', $flags ) && !in_array( 'T', $flags ) ) {
1341 $this->mFlags
= $flags = array( 'R' );
1345 if ( in_array( 'R', $flags ) ) {
1346 // if we don't do content convert, still strip the -{}- tags
1347 $this->mRuleDisplay
= $rules;
1348 } elseif ( in_array( 'N', $flags ) ) {
1349 // proces N flag: output current variant name
1350 $this->mRuleDisplay
=
1351 $this->mConverter
->mVariantNames
[ trim( $rules ) ];
1352 } elseif ( in_array( 'D', $flags ) ) {
1353 // proces D flag: output rules description
1354 $this->mRuleDisplay
= $this->getRulesDesc();
1355 } elseif ( in_array( 'H', $flags ) ||
in_array( '-', $flags ) ) {
1356 // proces H,- flag or T only: output nothing
1357 $this->mRuleDisplay
= '';
1358 } elseif ( in_array( 'S', $flags ) ) {
1359 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant,
1360 $this->mConverter
->mDoContentConvert
);
1362 $this->mRuleDisplay
= $this->mManualCodeError
;
1365 if ( in_array( 'T', $flags ) ) {
1366 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant,
1367 $this->mConverter
->mDoTitleConvert
);
1370 if ( in_array( '-', $flags ) ) {
1371 $this->mRulesAction
= 'remove';
1373 if ( in_array( '+', $flags ) ) {
1374 $this->mRulesAction
= 'add';
1377 $this->generateConvTable();
1383 function hasRules() {
1388 * Get display text on markup -{...}-
1391 function getDisplay() {
1392 return $this->mRuleDisplay
;
1396 * Get converted title.
1399 function getTitle() {
1400 return $this->mRuleTitle
;
1404 * Return how deal with conversion rules.
1407 function getRulesAction() {
1408 return $this->mRulesAction
;
1412 * Get conversion table. ( bidirectional and unidirectional
1413 * conversion table )
1416 function getConvTable() {
1417 return $this->mConvTable
;
1421 * Get conversion rules string.
1424 function getRules() {
1425 return $this->mRules
;
1429 * Get conversion flags.
1432 function getFlags() {
1433 return $this->mFlags
;