3 * Contains the LanguageConverter class and ConverterRule class
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Base class for language conversion.
28 * @author Zhengzhu Feng <zhengzhu@gmail.com>
29 * @maintainers fdcn <fdcn64@gmail.com>, shinjiman <shinjiman@gmail.com>, PhiLiP <philip.npc@gmail.com>
31 class LanguageConverter
{
32 var $mMainLanguageCode;
33 var $mVariants, $mVariantFallbacks, $mVariantNames;
34 var $mTablesLoaded = false;
36 // 'bidirectional' 'unidirectional' 'disable' for each variant
41 var $mDescCodeSep = ':', $mDescVarSep = ';';
42 var $mUcfirst = false;
43 var $mConvRuleTitle = false;
48 var $mVarSeparatorPattern;
50 const CACHE_VERSION_KEY
= 'VERSION 6';
55 * @param $langobj The Language Object
56 * @param $maincode String: the main language code of this language
57 * @param $variants Array: the supported variants of this language
58 * @param $variantfallbacks Array: the fallback language of each variant
59 * @param $flags Array: defining the custom strings that maps to the flags
60 * @param $manualLevel Array: limit for supported variants
62 public function __construct( $langobj, $maincode,
64 $variantfallbacks = array(),
66 $manualLevel = array() ) {
67 global $wgDisabledVariants, $wgLanguageNames;
68 $this->mLangObj
= $langobj;
69 $this->mMainLanguageCode
= $maincode;
70 $this->mVariants
= array_diff( $variants, $wgDisabledVariants );
71 $this->mVariantFallbacks
= $variantfallbacks;
72 $this->mVariantNames
= $wgLanguageNames;
73 $this->mCacheKey
= wfMemcKey( 'conversiontables', $maincode );
74 $defaultflags = array(
75 // 'S' show converted text
76 // '+' add rules for alltext
77 // 'E' the gave flags is error
78 // these flags above are reserved for program
79 'A' => 'A', // add rule for convert code (all text convert)
80 'T' => 'T', // title convert
81 'R' => 'R', // raw content
82 'D' => 'D', // convert description (subclass implement)
83 '-' => '-', // remove convert (not implement)
84 'H' => 'H', // add rule for convert code
85 // (but no display in placed code )
86 'N' => 'N' // current variant name
88 $this->mFlags
= array_merge( $defaultflags, $flags );
89 foreach ( $this->mVariants
as $v ) {
90 if ( array_key_exists( $v, $manualLevel ) ) {
91 $this->mManualLevel
[$v] = $manualLevel[$v];
93 $this->mManualLevel
[$v] = 'bidirectional';
95 $this->mFlags
[$v] = $v;
100 * Get all valid variants.
101 * Call this instead of using $this->mVariants directly.
103 * @return Array: contains all valid variants
105 public function getVariants() {
106 return $this->mVariants
;
110 * In case some variant is not defined in the markup, we need
111 * to have some fallback. For example, in zh, normally people
112 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
113 * when zh-sg is preferred but not defined, we will pick zh-hans
114 * in this case. Right now this is only used by zh.
116 * @param $variant String: the language code of the variant
117 * @return String: The code of the fallback language or the
118 * main code if there is no fallback
120 public function getVariantFallbacks( $variant ) {
121 if ( isset( $this->mVariantFallbacks
[$variant] ) ) {
122 return $this->mVariantFallbacks
[$variant];
124 return $this->mMainLanguageCode
;
128 * Get the title produced by the conversion rule.
129 * @return String: The converted title text
131 public function getConvRuleTitle() {
132 return $this->mConvRuleTitle
;
136 * Get preferred language variant.
137 * @param $fromUser Boolean: get it from $wgUser's preferences
138 * @param $fromHeader Boolean: get it from Accept-Language
139 * @return String: the preferred language code
141 public function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
142 global $wgDefaultLanguageVariant;
144 $req = $this->getURLVariant();
146 if ( $fromUser && !$req ) {
147 $req = $this->getUserVariant();
150 if ( $fromHeader && !$req ) {
151 $req = $this->getHeaderVariant();
154 if ( $wgDefaultLanguageVariant && !$req ) {
155 $req = $this->validateVariant( $wgDefaultLanguageVariant );
158 // This function, unlike the other get*Variant functions, is
159 // not memoized (i.e. there return value is not cached) since
160 // new information might appear during processing after this
165 return $this->mMainLanguageCode
;
169 * Validate the variant
170 * @param $variant String: the variant to validate
171 * @return Mixed: returns the variant if it is valid, null otherwise
173 protected function validateVariant( $variant = null ) {
174 if ( $variant !== null &&
175 in_array( $variant, $this->mVariants
) ) {
182 * Get the variant specified in the URL
184 * @return Mixed: variant if one found, false otherwise.
186 protected function getURLVariant() {
189 if ( $this->mURLVariant
) {
190 return $this->mURLVariant
;
193 // see if the preference is set in the request
194 $ret = $wgRequest->getText( 'variant' );
197 $ret = $wgRequest->getVal( 'uselang' );
200 return $this->mURLVariant
= $this->validateVariant( $ret );
204 * Determine if the user has a variant set.
206 * @return Mixed: variant if one found, false otherwise.
208 protected function getUserVariant() {
211 // memoizing this function wreaks havoc on parserTest.php
212 /* if ( $this->mUserVariant ) { */
213 /* return $this->mUserVariant; */
216 // get language variant preference from logged in users
217 // Don't call this on stub objects because that causes infinite
218 // recursion during initialisation
219 if ( $wgUser->isLoggedIn() ) {
220 $ret = $wgUser->getOption( 'variant' );
223 // figure out user lang without constructing wgLang to avoid
224 // infinite recursion
225 $ret = $wgUser->getOption( 'language' );
228 return $this->mUserVariant
= $this->validateVariant( $ret );
232 * Determine the language variant from the Accept-Language header.
234 * @return Mixed: variant if one found, false otherwise.
236 protected function getHeaderVariant() {
239 if ( $this->mHeaderVariant
) {
240 return $this->mHeaderVariant
;
243 // see if some supported language variant is set in the
245 $languages = array_keys( $wgRequest->getAcceptLang() );
246 if ( empty( $languages ) ) {
250 $fallback_languages = array();
251 foreach ( $languages as $language ) {
252 $this->mHeaderVariant
= $this->validateVariant( $language );
253 if ( $this->mHeaderVariant
) {
257 // To see if there are fallbacks of current language.
258 // We record these fallback variants, and process
260 $fallbacks = $this->getVariantFallbacks( $language );
261 if ( is_string( $fallbacks ) ) {
262 $fallback_languages[] = $fallbacks;
263 } elseif ( is_array( $fallbacks ) ) {
264 $fallback_languages =
265 array_merge( $fallback_languages,
270 if ( !$this->mHeaderVariant
) {
271 // process fallback languages now
272 $fallback_languages = array_unique( $fallback_languages );
273 foreach ( $fallback_languages as $language ) {
274 $this->mHeaderVariant
= $this->validateVariant( $language );
275 if ( $this->mHeaderVariant
) {
281 return $this->mHeaderVariant
;
285 * Caption convert, base on preg_replace_callback.
287 * To convert text in "title" or "alt", like '<img alt="text" ... '
288 * or '<span title="text" ... '
290 * @return String like ' alt="yyyy"' or ' title="yyyy"'
292 protected function captionConvert( $matches ) {
293 $toVariant = $this->getPreferredVariant();
294 $title = $matches[1];
296 // we convert captions except URL
297 if ( !strpos( $text, '://' ) ) {
298 $text = $this->translate( $text, $toVariant );
300 return " $title=\"$text\"";
304 * Dictionary-based conversion.
305 * This function would not parse the conversion rules.
306 * If you want to parse rules, try to use convert() or
309 * @param $text String: the text to be converted
310 * @param $toVariant String: the target language code
311 * @return String: the converted text
313 public function autoConvert( $text, $toVariant = false ) {
314 wfProfileIn( __METHOD__
);
319 $toVariant = $this->getPreferredVariant();
325 /* we convert everything except:
326 1. html markups (anything between < and >)
328 3. place holders created by the parser
331 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
332 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
337 // this one is needed when the text is inside an html markup
338 $htmlfix = '|<[^>]+$|^[^<>]*>';
340 // disable convert to variants between <code></code> tags
341 $codefix = '<code>.+?<\/code>|';
342 // disable convertsion of <script type="text/javascript"> ... </script>
343 $scriptfix = '<script.*?>.*?<\/script>|';
344 // disable conversion of <pre xxxx> ... </pre>
345 $prefix = '<pre.*?>.*?<\/pre>|';
347 $reg = '/' . $codefix . $scriptfix . $prefix .
348 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
350 $matches = preg_split( $reg, $text, - 1, PREG_SPLIT_OFFSET_CAPTURE
);
352 $m = array_shift( $matches );
354 $ret = $this->translate( $m[0], $toVariant );
355 $mstart = $m[1] +
strlen( $m[0] );
357 // enable convertsion of '<img alt="xxxx" ... '
358 // or '<span title="xxxx" ... '
359 $captionpattern = '/\s(title|alt)\s*=\s*"([\s\S]*?)"/';
364 foreach ( $matches as $m ) {
365 $mark = substr( $text, $mstart, $m[1] - $mstart );
366 $mark = preg_replace_callback( $captionpattern,
367 array( &$this, 'captionConvert' ),
369 // Let's convert the trtext only once,
370 // it would give us more performance improvement
372 $trtext .= $m[0] . $trtextmark;
373 $mstart = $m[1] +
strlen( $m[0] );
376 $trtext = $this->translate( $trtext, $toVariant );
377 $trtext = StringUtils
::explode( $trtextmark, $trtext );
378 foreach ( $trtext as $t ) {
379 $ret .= array_shift( $notrtext );
382 wfProfileOut( __METHOD__
);
387 * Translate a string to a variant.
388 * Doesn't parse rules or do any of that other stuff, for that use
389 * convert() or convertTo().
391 * @param $text String: text to convert
392 * @param $variant String: variant language code
393 * @return String: translated text
395 protected function translate( $text, $variant ) {
396 wfProfileIn( __METHOD__
);
397 // If $text is empty or only includes spaces, do nothing
398 // Otherwise translate it
399 if ( trim( $text ) ) {
401 $text = $this->mTables
[$variant]->replace( $text );
403 wfProfileOut( __METHOD__
);
408 * Call translate() to convert text to all valid variants.
410 * @param $text String: the text to be converted
411 * @return Array: variant => converted text
413 public function autoConvertToAllVariants( $text ) {
414 wfProfileIn( __METHOD__
);
418 foreach ( $this->mVariants
as $variant ) {
419 $ret[$variant] = $this->translate( $text, $variant );
422 wfProfileOut( __METHOD__
);
427 * Convert link text to all valid variants.
428 * In the first, this function only convert text outside the
429 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
430 * titles, the text will get all converted always.
431 * So I removed this feature and deprecated the function.
433 * @param $text String: the text to be converted
434 * @return Array: variant => converted text
435 * @deprecated Use autoConvertToAllVariants() instead
437 public function convertLinkToAllVariants( $text ) {
438 return $this->autoConvertToAllVariants( $text );
442 * Apply manual conversion rules.
444 * @param $convRule Object: Object of ConverterRule
446 protected function applyManualConv( $convRule ) {
447 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
449 // Bug 24072: $mConvRuleTitle was overwritten by other manual
450 // rule(s) not for title, this breaks the title conversion.
451 $newConvRuleTitle = $convRule->getTitle();
452 if ( $newConvRuleTitle ) {
453 // So I add an empty check for getTitle()
454 $this->mConvRuleTitle
= $newConvRuleTitle;
457 // merge/remove manual conversion rules to/from global table
458 $convTable = $convRule->getConvTable();
459 $action = $convRule->getRulesAction();
460 foreach ( $convTable as $variant => $pair ) {
461 if ( !$this->validateVariant( $variant ) ) {
465 if ( $action == 'add' ) {
466 foreach ( $pair as $from => $to ) {
467 // to ensure that $from and $to not be left blank
468 // so $this->translate() could always return a string
469 if ( $from ||
$to ) {
470 // more efficient than array_merge(), about 2.5 times.
471 $this->mTables
[$variant]->setPair( $from, $to );
474 } elseif ( $action == 'remove' ) {
475 $this->mTables
[$variant]->removeArray( $pair );
481 * Auto convert a Title object to a readable string in the
484 *@param $title Object: a object of Title
485 *@return String: converted title text
487 public function convertTitle( $title ) {
488 $variant = $this->getPreferredVariant();
489 $index = $title->getNamespace();
490 if ( $index === NS_MAIN
) {
493 // first let's check if a message has given us a converted name
494 $nsConvKey = 'conversion-ns' . $index;
495 if ( !wfEmptyMsg( $nsConvKey ) ) {
496 $text = wfMsgForContentNoTrans( $nsConvKey );
498 // the message does not exist, try retrieve it from the current
499 // variant's namespace names.
500 $langObj = $this->mLangObj
->factory( $variant );
501 $text = $langObj->getFormattedNsText( $index );
505 $text .= $title->getText();
506 $text = $this->translate( $text, $variant );
511 * Convert text to different variants of a language. The automatic
512 * conversion is done in autoConvert(). Here we parse the text
513 * marked with -{}-, which specifies special conversions of the
514 * text that can not be accomplished in autoConvert().
516 * Syntax of the markup:
517 * -{code1:text1;code2:text2;...}- or
518 * -{flags|code1:text1;code2:text2;...}- or
519 * -{text}- in which case no conversion should take place for text
521 * @param $text String: text to be converted
522 * @return String: converted text
524 public function convert( $text ) {
525 $variant = $this->getPreferredVariant();
526 return $this->convertTo( $text, $variant );
530 * Same as convert() except a extra parameter to custom variant.
532 * @param $text String: text to be converted
533 * @param $variant String: the target variant code
534 * @return String: converted text
536 public function convertTo( $text, $variant ) {
537 global $wgDisableLangConversion;
538 if ( $wgDisableLangConversion ) return $text;
539 return $this->recursiveConvertTopLevel( $text, $variant );
543 * Recursively convert text on the outside. Allow to use nested
544 * markups to custom rules.
546 * @param $text String: text to be converted
547 * @param $variant String: the target variant code
548 * @param $depth Integer: depth of recursion
549 * @return String: converted text
551 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
554 $length = strlen( $text );
555 while ( $startPos < $length ) {
556 $pos = strpos( $text, '-{', $startPos );
558 if ( $pos === false ) {
559 // No more markup, append final segment
560 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
565 // Append initial segment
566 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
571 // Do recursive conversion
572 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
579 * Recursively convert text on the inside.
581 * @param $text String: text to be converted
582 * @param $variant String: the target variant code
583 * @param $depth Integer: depth of recursion
584 * @return String: converted text
586 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
587 // Quick sanity check (no function calls)
588 if ( $text[$startPos] !== '-' ||
$text[$startPos +
1] !== '{' ) {
589 throw new MWException( __METHOD__
. ': invalid input string' );
594 $warningDone = false;
595 $length = strlen( $text );
597 while ( $startPos < $length ) {
599 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE
, $startPos );
609 // Append initial segment
610 $inner .= substr( $text, $startPos, $pos - $startPos );
618 if ( $depth >= $this->mMaxDepth
) {
620 if ( !$warningDone ) {
621 $inner .= '<span class="error">' .
622 wfMsgForContent( 'language-converter-depth-warning',
630 // Recursively parse another rule
631 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth +
1 );
636 $rule = new ConverterRule( $inner, $this );
637 $rule->parse( $variant );
638 $this->applyManualConv( $rule );
639 return $rule->getDisplay();
641 throw new MWException( __METHOD__
. ': invalid regex match' );
646 if ( $startPos < $length ) {
647 $inner .= substr( $text, $startPos );
650 return '-{' . $this->autoConvert( $inner, $variant );
654 * If a language supports multiple variants, it is
655 * possible that non-existing link in one variant
656 * actually exists in another variant. This function
657 * tries to find it. See e.g. LanguageZh.php
659 * @param $link String: the name of the link
660 * @param $nt Mixed: the title object of the link
661 * @param $ignoreOtherCond Boolean: to disable other conditions when
662 * we need to transclude a template or update a category's link
663 * @return Null, the input parameters may be modified upon return
665 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
666 # If the article has already existed, there is no need to
667 # check it again, otherwise it may cause a fault.
668 if ( is_object( $nt ) && $nt->exists() ) {
672 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
674 $isredir = $wgRequest->getText( 'redirect', 'yes' );
675 $action = $wgRequest->getText( 'action' );
676 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
677 $disableLinkConversion = $wgDisableLangConversion
678 ||
$wgDisableTitleConversion;
679 $linkBatch = new LinkBatch();
683 if ( $disableLinkConversion ||
684 ( !$ignoreOtherCond &&
687 ||
$action == 'submit'
688 ||
$linkconvert == 'no'
689 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
693 if ( is_object( $nt ) ) {
694 $ns = $nt->getNamespace();
697 $variants = $this->autoConvertToAllVariants( $link );
698 if ( !$variants ) { // give up
704 foreach ( $variants as $v ) {
706 $varnt = Title
::newFromText( $v, $ns );
707 if ( !is_null( $varnt ) ) {
708 $linkBatch->addObj( $varnt );
714 // fetch all variants in single query
715 $linkBatch->execute();
717 foreach ( $titles as $varnt ) {
718 if ( $varnt->getArticleID() > 0 ) {
720 $link = $varnt->getText();
727 * Returns language specific hash options.
729 public function getExtraHashOptions() {
730 $variant = $this->getPreferredVariant();
731 return '!' . $variant ;
735 * Load default conversion tables.
736 * This method must be implemented in derived class.
740 function loadDefaultTables() {
741 $name = get_class( $this );
742 wfDie( "Must implement loadDefaultTables() method in class $name" );
746 * Load conversion tables either from the cache or the disk.
749 function loadTables( $fromcache = true ) {
750 if ( $this->mTablesLoaded
) {
754 wfProfileIn( __METHOD__
);
755 $this->mTablesLoaded
= true;
756 $this->mTables
= false;
758 wfProfileIn( __METHOD__
. '-cache' );
759 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
760 wfProfileOut( __METHOD__
. '-cache' );
763 ||
!array_key_exists( self
::CACHE_VERSION_KEY
, $this->mTables
) ) {
764 wfProfileIn( __METHOD__
. '-recache' );
765 // not in cache, or we need a fresh reload.
766 // we will first load the default tables
767 // then update them using things in MediaWiki:Zhconversiontable/*
768 $this->loadDefaultTables();
769 foreach ( $this->mVariants
as $var ) {
770 $cached = $this->parseCachedTable( $var );
771 $this->mTables
[$var]->mergeArray( $cached );
774 $this->postLoadTables();
775 $this->mTables
[self
::CACHE_VERSION_KEY
] = true;
777 $wgMemc->set( $this->mCacheKey
, $this->mTables
, 43200 );
778 wfProfileOut( __METHOD__
. '-recache' );
780 wfProfileOut( __METHOD__
);
784 * Hook for post processig after conversion tables are loaded.
787 function postLoadTables() { }
790 * Reload the conversion tables.
794 function reloadTables() {
795 if ( $this->mTables
) {
796 unset( $this->mTables
);
798 $this->mTablesLoaded
= false;
799 $this->loadTables( false );
804 * Parse the conversion table stored in the cache.
806 * The tables should be in blocks of the following form:
813 * To make the tables more manageable, subpages are allowed
814 * and will be parsed recursively if $recursive == true.
817 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
818 global $wgMessageCache;
819 static $parsed = array();
821 if ( !is_object( $wgMessageCache ) ) {
825 $key = 'Conversiontable/' . $code;
827 $key .= '/' . $subpage;
829 if ( array_key_exists( $key, $parsed ) ) {
833 if ( strpos( $code, '/' ) === false ) {
834 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
835 if ( $txt === false ) {
836 # FIXME: this method doesn't seem to be expecting
837 # this possible outcome...
838 $txt = '<Conversiontable>';
841 $title = Title
::makeTitleSafe( NS_MEDIAWIKI
,
842 "Conversiontable/$code" );
843 if ( $title && $title->exists() ) {
844 $article = new Article( $title );
845 $txt = $article->getContents();
851 // get all subpage links of the form
852 // [[MediaWiki:conversiontable/zh-xx/...|...]]
853 $linkhead = $this->mLangObj
->getNsText( NS_MEDIAWIKI
) .
855 $subs = StringUtils
::explode( '[[', $txt );
857 foreach ( $subs as $sub ) {
858 $link = explode( ']]', $sub, 2 );
859 if ( count( $link ) != 2 ) {
862 $b = explode( '|', $link[0], 2 );
863 $b = explode( '/', trim( $b[0] ), 3 );
864 if ( count( $b ) == 3 ) {
870 if ( $b[0] == $linkhead && $b[1] == $code ) {
871 $sublinks[] = $sublink;
875 // parse the mappings in this page
876 $blocks = StringUtils
::explode( '-{', $txt );
879 foreach ( $blocks as $block ) {
881 // Skip the part before the first -{
885 $mappings = explode( '}-', $block, 2 );
886 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
888 $table = StringUtils
::explode( ';', $stripped );
889 foreach ( $table as $t ) {
890 $m = explode( '=>', $t, 3 );
891 if ( count( $m ) != 2 )
893 // trim any trailling comments starting with '//'
894 $tt = explode( '//', $m[1], 2 );
895 $ret[trim( $m[0] )] = trim( $tt[0] );
898 $parsed[$key] = true;
900 // recursively parse the subpages
902 foreach ( $sublinks as $link ) {
903 $s = $this->parseCachedTable( $code, $link, $recursive );
904 $ret = array_merge( $ret, $s );
908 if ( $this->mUcfirst
) {
909 foreach ( $ret as $k => $v ) {
910 $ret[$this->mLangObj
->ucfirst( $k )] = $this->mLangObj
->ucfirst( $v );
917 * Enclose a string with the "no conversion" tag. This is used by
918 * various functions in the Parser.
920 * @param $text String: text to be tagged for no conversion
921 * @param $noParse Unused (?)
922 * @return String: the tagged text
924 public function markNoConversion( $text, $noParse = false ) {
925 # don't mark if already marked
926 if ( strpos( $text, '-{' ) ||
strpos( $text, '}-' ) ) {
930 $ret = "-{R|$text}-";
935 * Convert the sorting key for category links. This should make different
936 * keys that are variants of each other map to the same key.
938 function convertCategoryKey( $key ) {
943 * Hook to refresh the cache of conversion tables when
944 * MediaWiki:conversiontable* is updated.
947 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
948 $iswatch, $section, $flags, $revision ) {
949 $titleobj = $article->getTitle();
950 if ( $titleobj->getNamespace() == NS_MEDIAWIKI
) {
951 $title = $titleobj->getDBkey();
952 $t = explode( '/', $title, 3 );
954 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
955 if ( $this->validateVariant( $t[1] ) ) {
956 $this->reloadTables();
964 * Armour rendered math against conversion.
965 * Wrap math into rawoutput -{R| math }- syntax.
967 public function armourMath( $text ) {
968 // we need to convert '-{' and '}-' to '-{' and '}-'
969 // to avoid a unwanted '}-' appeared after the math-image.
970 $text = strtr( $text, array( '-{' => '-{', '}-' => '}-' ) );
971 $ret = "-{R|$text}-";
976 * Get the cached separator pattern for ConverterRule::parseRules()
978 function getVarSeparatorPattern() {
979 if ( is_null( $this->mVarSeparatorPattern
) ) {
980 // varsep_pattern for preg_split:
981 // text should be splited by ";" only if a valid variant
982 // name exist after the markup, for example:
983 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
984 // <span style="font-size:120%;">yyy</span>;}-
985 // we should split it as:
987 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
988 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
992 foreach ( $this->mVariants
as $variant ) {
993 // zh-hans:xxx;zh-hant:yyy
994 $pat .= $variant . '\s*:|';
995 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
996 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
999 $this->mVarSeparatorPattern
= $pat;
1001 return $this->mVarSeparatorPattern
;
1006 * Parser for rules of language conversion , parse rules in -{ }- tag.
1008 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1010 class ConverterRule
{
1011 var $mText; // original text in -{text}-
1012 var $mConverter; // LanguageConverter object
1013 var $mManualCodeError = '<strong class="error">code error!</strong>';
1014 var $mRuleDisplay = '';
1015 var $mRuleTitle = false;
1016 var $mRules = '';// string : the text of the rules
1017 var $mRulesAction = 'none';
1018 var $mFlags = array();
1019 var $mVariantFlags = array();
1020 var $mConvTable = array();
1021 var $mBidtable = array();// array of the translation in each variant
1022 var $mUnidtable = array();// array of the translation in each variant
1027 * @param $text String: the text between -{ and }-
1028 * @param $converter LanguageConverter object
1030 public function __construct( $text, $converter ) {
1031 $this->mText
= $text;
1032 $this->mConverter
= $converter;
1036 * Check if variants array in convert array.
1038 * @param $variants Array or string: variant language code
1039 * @return String: translated text
1041 public function getTextInBidtable( $variants ) {
1042 $variants = (array)$variants;
1046 foreach ( $variants as $variant ) {
1047 if ( isset( $this->mBidtable
[$variant] ) ) {
1048 return $this->mBidtable
[$variant];
1055 * Parse flags with syntax -{FLAG| ... }-
1058 function parseFlags() {
1059 $text = $this->mText
;
1061 $variantFlags = array();
1063 $sepPos = strpos( $text, '|' );
1064 if ( $sepPos !== false ) {
1065 $validFlags = $this->mConverter
->mFlags
;
1066 $f = StringUtils
::explode( ';', substr( $text, 0, $sepPos ) );
1067 foreach ( $f as $ff ) {
1069 if ( isset( $validFlags[$ff] ) ) {
1070 $flags[$validFlags[$ff]] = true;
1073 $text = strval( substr( $text, $sepPos +
1 ) );
1078 } elseif ( isset( $flags['R'] ) ) {
1079 $flags = array( 'R' => true );// remove other flags
1080 } elseif ( isset( $flags['N'] ) ) {
1081 $flags = array( 'N' => true );// remove other flags
1082 } elseif ( isset( $flags['-'] ) ) {
1083 $flags = array( '-' => true );// remove other flags
1084 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1086 } elseif ( isset( $flags['H'] ) ) {
1087 // replace A flag, and remove other flags except T
1088 $temp = array( '+' => true, 'H' => true );
1089 if ( isset( $flags['T'] ) ) {
1092 if ( isset( $flags['D'] ) ) {
1097 if ( isset( $flags['A'] ) ) {
1101 if ( isset( $flags['D'] ) ) {
1102 unset( $flags['S'] );
1104 // try to find flags like "zh-hans", "zh-hant"
1105 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1106 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter
->mVariants
);
1107 if ( $variantFlags ) {
1108 $variantFlags = array_flip( $variantFlags );
1112 $this->mVariantFlags
= $variantFlags;
1113 $this->mRules
= $text;
1114 $this->mFlags
= $flags;
1118 * Generate conversion table.
1121 function parseRules() {
1122 $rules = $this->mRules
;
1123 $bidtable = array();
1124 $unidtable = array();
1125 $variants = $this->mConverter
->mVariants
;
1126 $varsep_pattern = $this->mConverter
->getVarSeparatorPattern();
1128 $choice = preg_split( $varsep_pattern, $rules );
1130 foreach ( $choice as $c ) {
1131 $v = explode( ':', $c, 2 );
1132 if ( count( $v ) != 2 ) {
1133 // syntax error, skip
1136 $to = trim( $v[1] );
1138 $u = explode( '=>', $v, 2 );
1139 // if $to is empty, strtr() could return a wrong result
1140 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1141 $bidtable[$v] = $to;
1142 } elseif ( count( $u ) == 2 ) {
1143 $from = trim( $u[0] );
1145 if ( array_key_exists( $v, $unidtable )
1146 && !is_array( $unidtable[$v] )
1148 && in_array( $v, $variants ) ) {
1149 $unidtable[$v] = array( $from => $to );
1150 } elseif ( $to && in_array( $v, $variants ) ) {
1151 $unidtable[$v][$from] = $to;
1154 // syntax error, pass
1155 if ( !isset( $this->mConverter
->mVariantNames
[$v] ) ) {
1156 $bidtable = array();
1157 $unidtable = array();
1161 $this->mBidtable
= $bidtable;
1162 $this->mUnidtable
= $unidtable;
1168 function getRulesDesc() {
1169 $codesep = $this->mConverter
->mDescCodeSep
;
1170 $varsep = $this->mConverter
->mDescVarSep
;
1172 foreach ( $this->mBidtable
as $k => $v ) {
1173 $text .= $this->mConverter
->mVariantNames
[$k] . "$codesep$v$varsep";
1175 foreach ( $this->mUnidtable
as $k => $a ) {
1176 foreach ( $a as $from => $to ) {
1177 $text .= $from . '⇒' . $this->mConverter
->mVariantNames
[$k] .
1178 "$codesep$to$varsep";
1185 * Parse rules conversion.
1188 function getRuleConvertedStr( $variant ) {
1189 $bidtable = $this->mBidtable
;
1190 $unidtable = $this->mUnidtable
;
1192 if ( count( $bidtable ) +
count( $unidtable ) == 0 ) {
1193 return $this->mRules
;
1195 // display current variant in bidirectional array
1196 $disp = $this->getTextInBidtable( $variant );
1197 // or display current variant in fallbacks
1199 $disp = $this->getTextInBidtable(
1200 $this->mConverter
->getVariantFallbacks( $variant ) );
1202 // or display current variant in unidirectional array
1203 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1204 $disp = array_values( $unidtable[$variant] );
1207 // or display frist text under disable manual convert
1209 && $this->mConverter
->mManualLevel
[$variant] == 'disable' ) {
1210 if ( count( $bidtable ) > 0 ) {
1211 $disp = array_values( $bidtable );
1214 $disp = array_values( $unidtable );
1215 $disp = array_values( $disp[0] );
1224 * Generate conversion table for all text.
1227 function generateConvTable() {
1228 // Special case optimisation
1229 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1230 $this->mConvTable
= array();
1234 $bidtable = $this->mBidtable
;
1235 $unidtable = $this->mUnidtable
;
1236 $manLevel = $this->mConverter
->mManualLevel
;
1239 foreach ( $this->mConverter
->mVariants
as $v ) {
1240 /* for bidirectional array
1241 fill in the missing variants, if any,
1243 if ( !isset( $bidtable[$v] ) ) {
1245 $this->mConverter
->getVariantFallbacks( $v );
1246 $vf = $this->getTextInBidtable( $variantFallbacks );
1248 $bidtable[$v] = $vf;
1252 if ( isset( $bidtable[$v] ) ) {
1253 foreach ( $vmarked as $vo ) {
1254 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1255 // or -{H|zh:WordZh;zh-tw:WordTw}-
1256 // or -{-|zh:WordZh;zh-tw:WordTw}-
1257 // to introduce a custom mapping between
1258 // words WordZh and WordTw in the whole text
1259 if ( $manLevel[$v] == 'bidirectional' ) {
1260 $this->mConvTable
[$v][$bidtable[$vo]] = $bidtable[$v];
1262 if ( $manLevel[$vo] == 'bidirectional' ) {
1263 $this->mConvTable
[$vo][$bidtable[$v]] = $bidtable[$vo];
1268 /*for unidirectional array fill to convert tables */
1269 if ( ( $manLevel[$v] == 'bidirectional' ||
$manLevel[$v] == 'unidirectional' )
1270 && isset( $unidtable[$v] ) )
1272 if ( isset( $this->mConvTable
[$v] ) ) {
1273 $this->mConvTable
[$v] = array_merge( $this->mConvTable
[$v], $unidtable[$v] );
1275 $this->mConvTable
[$v] = $unidtable[$v];
1282 * Parse rules and flags.
1285 function parse( $variant = NULL ) {
1287 $variant = $this->mConverter
->getPreferredVariant();
1290 $this->parseFlags();
1291 $flags = $this->mFlags
;
1293 // convert to specified variant
1294 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1295 if ( $this->mVariantFlags
) {
1296 // check if current variant in flags
1297 if ( isset( $this->mVariantFlags
[$variant] ) ) {
1298 // then convert <text to convert> to current language
1299 $this->mRules
= $this->mConverter
->autoConvert( $this->mRules
,
1301 } else { // if current variant no in flags,
1302 // then we check its fallback variants.
1304 $this->mConverter
->getVariantFallbacks( $variant );
1305 foreach ( $variantFallbacks as $variantFallback ) {
1306 // if current variant's fallback exist in flags
1307 if ( isset( $this->mVariantFlags
[$variantFallback] ) ) {
1308 // then convert <text to convert> to fallback language
1310 $this->mConverter
->autoConvert( $this->mRules
,
1316 $this->mFlags
= $flags = array( 'R' => true );
1319 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1320 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1321 $this->mRules
= str_replace( '=>', '=>', $this->mRules
);
1322 $this->parseRules();
1324 $rules = $this->mRules
;
1326 if ( !$this->mBidtable
&& !$this->mUnidtable
) {
1327 if ( isset( $flags['+'] ) ||
isset( $flags['-'] ) ) {
1328 // fill all variants if text in -{A/H/-|text} without rules
1329 foreach ( $this->mConverter
->mVariants
as $v ) {
1330 $this->mBidtable
[$v] = $rules;
1332 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1333 $this->mFlags
= $flags = array( 'R' => true );
1337 $this->mRuleDisplay
= false;
1338 foreach ( $flags as $flag => $unused ) {
1341 // if we don't do content convert, still strip the -{}- tags
1342 $this->mRuleDisplay
= $rules;
1345 // process N flag: output current variant name
1346 $ruleVar = trim( $rules );
1347 if ( isset( $this->mConverter
->mVariantNames
[$ruleVar] ) ) {
1348 $this->mRuleDisplay
= $this->mConverter
->mVariantNames
[$ruleVar];
1350 $this->mRuleDisplay
= '';
1354 // process D flag: output rules description
1355 $this->mRuleDisplay
= $this->getRulesDesc();
1358 // process H,- flag or T only: output nothing
1359 $this->mRuleDisplay
= '';
1362 $this->mRulesAction
= 'remove';
1363 $this->mRuleDisplay
= '';
1366 $this->mRulesAction
= 'add';
1367 $this->mRuleDisplay
= '';
1370 $this->mRuleDisplay
= $this->getRuleConvertedStr( $variant );
1373 $this->mRuleTitle
= $this->getRuleConvertedStr( $variant );
1374 $this->mRuleDisplay
= '';
1377 // ignore unknown flags (but see error case below)
1380 if ( $this->mRuleDisplay
=== false ) {
1381 $this->mRuleDisplay
= $this->mManualCodeError
;
1384 $this->generateConvTable();
1390 function hasRules() {
1395 * Get display text on markup -{...}-
1398 function getDisplay() {
1399 return $this->mRuleDisplay
;
1403 * Get converted title.
1406 function getTitle() {
1407 return $this->mRuleTitle
;
1411 * Return how deal with conversion rules.
1414 function getRulesAction() {
1415 return $this->mRulesAction
;
1419 * Get conversion table. ( bidirectional and unidirectional
1420 * conversion table )
1423 function getConvTable() {
1424 return $this->mConvTable
;
1428 * Get conversion rules string.
1431 function getRules() {
1432 return $this->mRules
;
1436 * Get conversion flags.
1439 function getFlags() {
1440 return $this->mFlags
;