Restored line accidentally removed in r70520
[mediawiki.git] / languages / LanguageConverter.php
blobe0081de66151ea78f48e82610cb1aa40f960f00c
1 <?php
3 /**
4 * Contains the LanguageConverter class and ConverterRule class
5 * @ingroup Language
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
8 * @file
9 */
11 /**
12 * Base class for language conversion.
13 * @ingroup Language
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;
22 var $mTables;
23 // 'bidirectional' 'unidirectional' 'disable' for each variant
24 var $mManualLevel;
25 var $mCacheKey;
26 var $mLangObj;
27 var $mFlags;
28 var $mDescCodeSep = ':', $mDescVarSep = ';';
29 var $mUcfirst = false;
30 var $mConvRuleTitle = false;
31 var $mURLVariant;
32 var $mUserVariant;
33 var $mHeaderVariant;
34 var $mMaxDepth = 10;
35 var $mVarSeparatorPattern;
37 const CACHE_VERSION_KEY = 'VERSION 6';
39 /**
40 * Constructor
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,
50 $variants = array(),
51 $variantfallbacks = array(),
52 $flags = 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];
79 } else {
80 $this->mManualLevel[$v] = 'bidirectional';
82 $this->mFlags[$v] = $v;
86 /**
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;
96 /**
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
148 // is first called.
149 if ( $req ) {
150 return $req;
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 ) ) {
163 return $variant;
165 return null;
169 * Get the variant specified in the URL
171 * @return Mixed: variant if one found, false otherwise.
173 protected function getURLVariant() {
174 global $wgRequest;
175 $ret = null;
177 if ( $this->mURLVariant ) {
178 return $this->mURLVariant;
181 // see if the preference is set in the request
182 $ret = $wgRequest->getText( 'variant' );
184 if ( !$ret ) {
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() {
197 global $wgUser;
198 $ret = null;
200 // memoizing this function wreaks havoc on parserTest.php
201 /* if ( $this->mUserVariant ) { */
202 /* return $this->mUserVariant; */
203 /* } */
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' );
211 else {
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() {
227 global $wgRequest;
228 $ret = null;
230 if ( $this->mHeaderVariant ) {
231 return $this->mHeaderVariant;
234 // see if some supported language variant is set in the
235 // http header.
236 $languages = array_keys( $wgRequest->getAcceptLang() );
237 if ( empty( $languages ) ) {
238 return null;
241 $fallback_languages = array();
242 foreach ( $languages as $language ) {
243 $this->mHeaderVariant = $this->validateVariant( $language );
244 if ( $this->mHeaderVariant ) {
245 break;
248 // To see if there are fallbacks of current language.
249 // We record these fallback variants, and process
250 // them later.
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,
257 $fallbacks );
261 if ( !$this->mHeaderVariant ) {
262 // process fallback languages now
263 $fallback_languages = array_unique( $fallback_languages );
264 foreach ( $fallback_languages as $language ) {
265 $this->mHeaderVariant = $this->validateVariant( $language );
266 if ( $this->mHeaderVariant ) {
267 break;
272 return $this->mHeaderVariant;
276 * Caption convert, base on preg_replace_callback.
278 * To convert text in "title" or "alt", like '<img alt="text" ... '
279 * or '<span title="text" ... '
281 * @return String like ' alt="yyyy"' or ' title="yyyy"'
283 protected function captionConvert( $matches ) {
284 $toVariant = $this->getPreferredVariant();
285 $title = $matches[1];
286 $text = $matches[2];
287 // we convert captions except URL
288 if ( !strpos( $text, '://' ) ) {
289 $text = $this->translate( $text, $toVariant );
291 return " $title=\"$text\"";
295 * Dictionary-based conversion.
296 * This function would not parse the conversion rules.
297 * If you want to parse rules, try to use convert() or
298 * convertTo().
300 * @param $text String: the text to be converted
301 * @param $toVariant String: the target language code
302 * @return String: the converted text
304 public function autoConvert( $text, $toVariant = false ) {
305 wfProfileIn( __METHOD__ );
307 $this->loadTables();
309 if ( !$toVariant ) {
310 $toVariant = $this->getPreferredVariant();
311 if ( !$toVariant ) {
312 return $text;
316 /* we convert everything except:
317 1. html markups (anything between < and >)
318 2. html entities
319 3. place holders created by the parser
321 global $wgParser;
322 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
323 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
324 } else {
325 $marker = '';
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]*?)"/';
352 $trtext = '';
353 $trtextmark = "\0";
354 $notrtext = array();
355 foreach ( $matches as $m ) {
356 $mark = substr( $text, $mstart, $m[1] - $mstart );
357 $mark = preg_replace_callback( $captionpattern,
358 array( &$this, 'captionConvert' ),
359 $mark );
360 // Let's convert the trtext only once,
361 // it would give us more performance improvement
362 $notrtext[] = $mark;
363 $trtext .= $m[0] . $trtextmark;
364 $mstart = $m[1] + strlen( $m[0] );
366 $notrtext[] = '';
367 $trtext = $this->translate( $trtext, $toVariant );
368 $trtext = StringUtils::explode( $trtextmark, $trtext );
369 foreach ( $trtext as $t ) {
370 $ret .= array_shift( $notrtext );
371 $ret .= $t;
373 wfProfileOut( __METHOD__ );
374 return $ret;
378 * Translate a string to a variant.
379 * Doesn't parse rules or do any of that other stuff, for that use
380 * convert() or convertTo().
382 * @param $text String: text to convert
383 * @param $variant String: variant language code
384 * @return String: translated text
386 protected function translate( $text, $variant ) {
387 wfProfileIn( __METHOD__ );
388 // If $text is empty or only includes spaces, do nothing
389 // Otherwise translate it
390 if ( trim( $text ) ) {
391 $this->loadTables();
392 $text = $this->mTables[$variant]->replace( $text );
394 wfProfileOut( __METHOD__ );
395 return $text;
399 * Call translate() to convert text to all valid variants.
401 * @param $text String: the text to be converted
402 * @return Array: variant => converted text
404 public function autoConvertToAllVariants( $text ) {
405 wfProfileIn( __METHOD__ );
406 $this->loadTables();
408 $ret = array();
409 foreach ( $this->mVariants as $variant ) {
410 $ret[$variant] = $this->translate( $text, $variant );
413 wfProfileOut( __METHOD__ );
414 return $ret;
418 * Convert link text to all valid variants.
419 * In the first, this function only convert text outside the
420 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
421 * titles, the text will get all converted always.
422 * So I removed this feature and deprecated the function.
424 * @param $text String: the text to be converted
425 * @return Array: variant => converted text
426 * @deprecated Use autoConvertToAllVariants() instead
428 public function convertLinkToAllVariants( $text ) {
429 return $this->autoConvertToAllVariants( $text );
433 * Apply manual conversion rules.
435 * @param $convRule Object: Object of ConverterRule
437 protected function applyManualConv( $convRule ) {
438 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
439 // title conversion.
440 // Bug 24072: $mConvRuleTitle was overwritten by other manual
441 // rule(s) not for title, this breaks the title conversion.
442 $newConvRuleTitle = $convRule->getTitle();
443 if ( $newConvRuleTitle ) {
444 // So I add an empty check for getTitle()
445 $this->mConvRuleTitle = $newConvRuleTitle;
448 // merge/remove manual conversion rules to/from global table
449 $convTable = $convRule->getConvTable();
450 $action = $convRule->getRulesAction();
451 foreach ( $convTable as $variant => $pair ) {
452 if ( !$this->validateVariant( $variant ) ) {
453 continue;
456 if ( $action == 'add' ) {
457 foreach ( $pair as $from => $to ) {
458 // to ensure that $from and $to not be left blank
459 // so $this->translate() could always return a string
460 if ( $from || $to ) {
461 // more efficient than array_merge(), about 2.5 times.
462 $this->mTables[$variant]->setPair( $from, $to );
465 } elseif ( $action == 'remove' ) {
466 $this->mTables[$variant]->removeArray( $pair );
472 * Auto convert a Title object to a readable string in the
473 * preferred variant.
475 *@param $title Object: a object of Title
476 *@return String: converted title text
478 public function convertTitle( $title ) {
479 $variant = $this->getPreferredVariant();
480 $index = $title->getNamespace();
481 if ( $index === NS_MAIN ) {
482 $text = '';
483 } else {
484 // first let's check if a message has given us a converted name
485 $nsConvKey = 'conversion-ns' . $index;
486 if ( !wfEmptyMsg( $nsConvKey ) ) {
487 $text = wfMsgForContentNoTrans( $nsConvKey );
488 } else {
489 // the message does not exist, try retrieve it from the current
490 // variant's namespace names.
491 $langObj = $this->mLangObj->factory( $variant );
492 $text = $langObj->getFormattedNsText( $index );
494 $text .= ':';
496 $text .= $title->getText();
497 $text = $this->translate( $text, $variant );
498 return $text;
502 * Convert text to different variants of a language. The automatic
503 * conversion is done in autoConvert(). Here we parse the text
504 * marked with -{}-, which specifies special conversions of the
505 * text that can not be accomplished in autoConvert().
507 * Syntax of the markup:
508 * -{code1:text1;code2:text2;...}- or
509 * -{flags|code1:text1;code2:text2;...}- or
510 * -{text}- in which case no conversion should take place for text
512 * @param $text String: text to be converted
513 * @return String: converted text
515 public function convert( $text ) {
516 $variant = $this->getPreferredVariant();
517 return $this->convertTo( $text, $variant );
521 * Same as convert() except a extra parameter to custom variant.
523 * @param $text String: text to be converted
524 * @param $variant String: the target variant code
525 * @return String: converted text
527 public function convertTo( $text, $variant ) {
528 global $wgDisableLangConversion;
529 if ( $wgDisableLangConversion ) return $text;
530 return $this->recursiveConvertTopLevel( $text, $variant );
534 * Recursively convert text on the outside. Allow to use nested
535 * markups to custom rules.
537 * @param $text String: text to be converted
538 * @param $variant String: the target variant code
539 * @param $depth Integer: depth of recursion
540 * @return String: converted text
542 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
543 $startPos = 0;
544 $out = '';
545 $length = strlen( $text );
546 while ( $startPos < $length ) {
547 $m = false;
548 $pos = strpos( $text, '-{', $startPos );
550 if ( $pos === false ) {
551 // No more markup, append final segment
552 $out .= $this->autoConvert( substr( $text, $startPos ), $variant );
553 $startPos = $length;
554 return $out;
557 // Markup found
558 // Append initial segment
559 $out .= $this->autoConvert( substr( $text, $startPos, $pos - $startPos ), $variant );
561 // Advance position
562 $startPos = $pos;
564 // Do recursive conversion
565 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
568 return $out;
572 * Recursively convert text on the inside.
574 * @param $text String: text to be converted
575 * @param $variant String: the target variant code
576 * @param $depth Integer: depth of recursion
577 * @return String: converted text
579 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
580 // Quick sanity check (no function calls)
581 if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
582 throw new MWException( __METHOD__ . ': invalid input string' );
585 $startPos += 2;
586 $inner = '';
587 $warningDone = false;
588 $length = strlen( $text );
590 while ( $startPos < $length ) {
591 $m = false;
592 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
593 if ( !$m ) {
594 // Unclosed rule
595 break;
598 $token = $m[0][0];
599 $pos = $m[0][1];
601 // Markup found
602 // Append initial segment
603 $inner .= substr( $text, $startPos, $pos - $startPos );
605 // Advance position
606 $startPos = $pos;
608 switch ( $token ) {
609 case '-{':
610 // Check max depth
611 if ( $depth >= $this->mMaxDepth ) {
612 $inner .= '-{';
613 if ( !$warningDone ) {
614 $inner .= '<span class="error">' .
615 wfMsgForContent( 'language-converter-depth-warning',
616 $this->mMaxDepth ) .
617 '</span>';
618 $warningDone = true;
620 $startPos += 2;
621 continue;
623 // Recursively parse another rule
624 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
625 break;
626 case '}-':
627 // Apply the rule
628 $startPos += 2;
629 $rule = new ConverterRule( $inner, $this );
630 $rule->parse( $variant );
631 $this->applyManualConv( $rule );
632 return $rule->getDisplay();
633 default:
634 throw new MWException( __METHOD__ . ': invalid regex match' );
638 // Unclosed rule
639 if ( $startPos < $length ) {
640 $inner .= substr( $text, $startPos );
642 $startPos = $length;
643 return '-{' . $this->autoConvert( $inner, $variant );
647 * If a language supports multiple variants, it is
648 * possible that non-existing link in one variant
649 * actually exists in another variant. This function
650 * tries to find it. See e.g. LanguageZh.php
652 * @param $link String: the name of the link
653 * @param $nt Mixed: the title object of the link
654 * @param $ignoreOtherCond Boolean: to disable other conditions when
655 * we need to transclude a template or update a category's link
656 * @return Null, the input parameters may be modified upon return
658 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
659 # If the article has already existed, there is no need to
660 # check it again, otherwise it may cause a fault.
661 if ( is_object( $nt ) && $nt->exists() ) {
662 return;
665 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
666 $wgUser;
667 $isredir = $wgRequest->getText( 'redirect', 'yes' );
668 $action = $wgRequest->getText( 'action' );
669 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
670 $disableLinkConversion = $wgDisableLangConversion
671 || $wgDisableTitleConversion;
672 $linkBatch = new LinkBatch();
674 $ns = NS_MAIN;
676 if ( $disableLinkConversion ||
677 ( !$ignoreOtherCond &&
678 ( $isredir == 'no'
679 || $action == 'edit'
680 || $action == 'submit'
681 || $linkconvert == 'no'
682 || $wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
683 return;
686 if ( is_object( $nt ) ) {
687 $ns = $nt->getNamespace();
690 $variants = $this->autoConvertToAllVariants( $link );
691 if ( !$variants ) { // give up
692 return;
695 $titles = array();
697 foreach ( $variants as $v ) {
698 if ( $v != $link ) {
699 $varnt = Title::newFromText( $v, $ns );
700 if ( !is_null( $varnt ) ) {
701 $linkBatch->addObj( $varnt );
702 $titles[] = $varnt;
707 // fetch all variants in single query
708 $linkBatch->execute();
710 foreach ( $titles as $varnt ) {
711 if ( $varnt->getArticleID() > 0 ) {
712 $nt = $varnt;
713 $link = $varnt->getText();
714 break;
720 * Returns language specific hash options.
722 public function getExtraHashOptions() {
723 $variant = $this->getPreferredVariant();
724 return '!' . $variant ;
728 * Load default conversion tables.
729 * This method must be implemented in derived class.
731 * @private
733 function loadDefaultTables() {
734 $name = get_class( $this );
735 wfDie( "Must implement loadDefaultTables() method in class $name" );
739 * Load conversion tables either from the cache or the disk.
740 * @private
742 function loadTables( $fromcache = true ) {
743 if ( $this->mTablesLoaded ) {
744 return;
746 global $wgMemc;
747 wfProfileIn( __METHOD__ );
748 $this->mTablesLoaded = true;
749 $this->mTables = false;
750 if ( $fromcache ) {
751 wfProfileIn( __METHOD__ . '-cache' );
752 $this->mTables = $wgMemc->get( $this->mCacheKey );
753 wfProfileOut( __METHOD__ . '-cache' );
755 if ( !$this->mTables
756 || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
757 wfProfileIn( __METHOD__ . '-recache' );
758 // not in cache, or we need a fresh reload.
759 // we will first load the default tables
760 // then update them using things in MediaWiki:Zhconversiontable/*
761 $this->loadDefaultTables();
762 foreach ( $this->mVariants as $var ) {
763 $cached = $this->parseCachedTable( $var );
764 $this->mTables[$var]->mergeArray( $cached );
767 $this->postLoadTables();
768 $this->mTables[self::CACHE_VERSION_KEY] = true;
770 $wgMemc->set( $this->mCacheKey, $this->mTables, 43200 );
771 wfProfileOut( __METHOD__ . '-recache' );
773 wfProfileOut( __METHOD__ );
777 * Hook for post processig after conversion tables are loaded.
780 function postLoadTables() { }
783 * Reload the conversion tables.
785 * @private
787 function reloadTables() {
788 if ( $this->mTables ) {
789 unset( $this->mTables );
791 $this->mTablesLoaded = false;
792 $this->loadTables( false );
797 * Parse the conversion table stored in the cache.
799 * The tables should be in blocks of the following form:
800 * -{
801 * word => word ;
802 * word => word ;
803 * ...
804 * }-
806 * To make the tables more manageable, subpages are allowed
807 * and will be parsed recursively if $recursive == true.
810 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
811 global $wgMessageCache;
812 static $parsed = array();
814 if ( !is_object( $wgMessageCache ) ) {
815 return array();
818 $key = 'Conversiontable/' . $code;
819 if ( $subpage ) {
820 $key .= '/' . $subpage;
822 if ( array_key_exists( $key, $parsed ) ) {
823 return array();
826 if ( strpos( $code, '/' ) === false ) {
827 $txt = $wgMessageCache->get( 'Conversiontable', true, $code );
828 if ( $txt === false ) {
829 # FIXME: this method doesn't seem to be expecting
830 # this possible outcome...
831 $txt = '&lt;Conversiontable&gt;';
833 } else {
834 $title = Title::makeTitleSafe( NS_MEDIAWIKI,
835 "Conversiontable/$code" );
836 if ( $title && $title->exists() ) {
837 $article = new Article( $title );
838 $txt = $article->getContents();
839 } else {
840 $txt = '';
844 // get all subpage links of the form
845 // [[MediaWiki:conversiontable/zh-xx/...|...]]
846 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
847 ':Conversiontable';
848 $subs = StringUtils::explode( '[[', $txt );
849 $sublinks = array();
850 foreach ( $subs as $sub ) {
851 $link = explode( ']]', $sub, 2 );
852 if ( count( $link ) != 2 ) {
853 continue;
855 $b = explode( '|', $link[0], 2 );
856 $b = explode( '/', trim( $b[0] ), 3 );
857 if ( count( $b ) == 3 ) {
858 $sublink = $b[2];
859 } else {
860 $sublink = '';
863 if ( $b[0] == $linkhead && $b[1] == $code ) {
864 $sublinks[] = $sublink;
868 // parse the mappings in this page
869 $blocks = StringUtils::explode( '-{', $txt );
870 $ret = array();
871 $first = true;
872 foreach ( $blocks as $block ) {
873 if ( $first ) {
874 // Skip the part before the first -{
875 $first = false;
876 continue;
878 $mappings = explode( '}-', $block, 2 );
879 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
880 $mappings[0] );
881 $table = StringUtils::explode( ';', $stripped );
882 foreach ( $table as $t ) {
883 $m = explode( '=>', $t, 3 );
884 if ( count( $m ) != 2 )
885 continue;
886 // trim any trailling comments starting with '//'
887 $tt = explode( '//', $m[1], 2 );
888 $ret[trim( $m[0] )] = trim( $tt[0] );
891 $parsed[$key] = true;
893 // recursively parse the subpages
894 if ( $recursive ) {
895 foreach ( $sublinks as $link ) {
896 $s = $this->parseCachedTable( $code, $link, $recursive );
897 $ret = array_merge( $ret, $s );
901 if ( $this->mUcfirst ) {
902 foreach ( $ret as $k => $v ) {
903 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
906 return $ret;
910 * Enclose a string with the "no conversion" tag. This is used by
911 * various functions in the Parser.
913 * @param $text String: text to be tagged for no conversion
914 * @param $noParse Unused (?)
915 * @return String: the tagged text
917 public function markNoConversion( $text, $noParse = false ) {
918 # don't mark if already marked
919 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
920 return $text;
923 $ret = "-{R|$text}-";
924 return $ret;
928 * Convert the sorting key for category links. This should make different
929 * keys that are variants of each other map to the same key.
931 function convertCategoryKey( $key ) {
932 return $key;
936 * Hook to refresh the cache of conversion tables when
937 * MediaWiki:conversiontable* is updated.
938 * @private
940 function OnArticleSaveComplete( $article, $user, $text, $summary, $isminor,
941 $iswatch, $section, $flags, $revision ) {
942 $titleobj = $article->getTitle();
943 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
944 $title = $titleobj->getDBkey();
945 $t = explode( '/', $title, 3 );
946 $c = count( $t );
947 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
948 if ( $this->validateVariant( $t[1] ) ) {
949 $this->reloadTables();
953 return true;
957 * Armour rendered math against conversion.
958 * Wrap math into rawoutput -{R| math }- syntax.
960 public function armourMath( $text ) {
961 // we need to convert '-{' and '}-' to '-&#123;' and '&#125;-'
962 // to avoid a unwanted '}-' appeared after the math-image.
963 $text = strtr( $text, array( '-{' => '-&#123;', '}-' => '&#125;-' ) );
964 $ret = "-{R|$text}-";
965 return $ret;
969 * Get the cached separator pattern for ConverterRule::parseRules()
971 function getVarSeparatorPattern() {
972 if ( is_null( $this->mVarSeparatorPattern ) ) {
973 // varsep_pattern for preg_split:
974 // text should be splited by ";" only if a valid variant
975 // name exist after the markup, for example:
976 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
977 // <span style="font-size:120%;">yyy</span>;}-
978 // we should split it as:
979 // array(
980 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
981 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
982 // [2] => ''
983 // )
984 $pat = '/;\s*(?=';
985 foreach ( $this->mVariants as $variant ) {
986 // zh-hans:xxx;zh-hant:yyy
987 $pat .= $variant . '\s*:|';
988 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
989 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
991 $pat .= '\s*$)/';
992 $this->mVarSeparatorPattern = $pat;
994 return $this->mVarSeparatorPattern;
999 * Parser for rules of language conversion , parse rules in -{ }- tag.
1000 * @ingroup Language
1001 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1003 class ConverterRule {
1004 var $mText; // original text in -{text}-
1005 var $mConverter; // LanguageConverter object
1006 var $mManualCodeError = '<strong class="error">code error!</strong>';
1007 var $mRuleDisplay = '';
1008 var $mRuleTitle = false;
1009 var $mRules = '';// string : the text of the rules
1010 var $mRulesAction = 'none';
1011 var $mFlags = array();
1012 var $mVariantFlags = array();
1013 var $mConvTable = array();
1014 var $mBidtable = array();// array of the translation in each variant
1015 var $mUnidtable = array();// array of the translation in each variant
1018 * Constructor
1020 * @param $text String: the text between -{ and }-
1021 * @param $converter LanguageConverter object
1023 public function __construct( $text, $converter ) {
1024 $this->mText = $text;
1025 $this->mConverter = $converter;
1029 * Check if variants array in convert array.
1031 * @param $variants Array or string: variant language code
1032 * @return String: translated text
1034 public function getTextInBidtable( $variants ) {
1035 $variants = (array)$variants;
1036 if ( !$variants ) {
1037 return false;
1039 foreach ( $variants as $variant ) {
1040 if ( isset( $this->mBidtable[$variant] ) ) {
1041 return $this->mBidtable[$variant];
1044 return false;
1048 * Parse flags with syntax -{FLAG| ... }-
1049 * @private
1051 function parseFlags() {
1052 $text = $this->mText;
1053 $flags = array();
1054 $variantFlags = array();
1056 $sepPos = strpos( $text, '|' );
1057 if ( $sepPos !== false ) {
1058 $validFlags = $this->mConverter->mFlags;
1059 $f = StringUtils::explode( ';', substr( $text, 0, $sepPos ) );
1060 foreach ( $f as $ff ) {
1061 $ff = trim( $ff );
1062 if ( isset( $validFlags[$ff] ) ) {
1063 $flags[$validFlags[$ff]] = true;
1066 $text = strval( substr( $text, $sepPos + 1 ) );
1069 if ( !$flags ) {
1070 $flags['S'] = true;
1071 } elseif ( isset( $flags['R'] ) ) {
1072 $flags = array( 'R' => true );// remove other flags
1073 } elseif ( isset( $flags['N'] ) ) {
1074 $flags = array( 'N' => true );// remove other flags
1075 } elseif ( isset( $flags['-'] ) ) {
1076 $flags = array( '-' => true );// remove other flags
1077 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1078 $flags['H'] = true;
1079 } elseif ( isset( $flags['H'] ) ) {
1080 // replace A flag, and remove other flags except T
1081 $temp = array( '+' => true, 'H' => true );
1082 if ( isset( $flags['T'] ) ) {
1083 $temp['T'] = true;
1085 if ( isset( $flags['D'] ) ) {
1086 $temp['D'] = true;
1088 $flags = $temp;
1089 } else {
1090 if ( isset( $flags['A'] ) ) {
1091 $flags['+'] = true;
1092 $flags['S'] = true;
1094 if ( isset( $flags['D'] ) ) {
1095 unset( $flags['S'] );
1097 // try to find flags like "zh-hans", "zh-hant"
1098 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1099 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter->mVariants );
1100 if ( $variantFlags ) {
1101 $variantFlags = array_flip( $variantFlags );
1102 $flags = array();
1105 $this->mVariantFlags = $variantFlags;
1106 $this->mRules = $text;
1107 $this->mFlags = $flags;
1111 * Generate conversion table.
1112 * @private
1114 function parseRules() {
1115 $rules = $this->mRules;
1116 $flags = $this->mFlags;
1117 $bidtable = array();
1118 $unidtable = array();
1119 $variants = $this->mConverter->mVariants;
1120 $varsep_pattern = $this->mConverter->getVarSeparatorPattern();
1122 $choice = preg_split( $varsep_pattern, $rules );
1124 foreach ( $choice as $c ) {
1125 $v = explode( ':', $c, 2 );
1126 if ( count( $v ) != 2 ) {
1127 // syntax error, skip
1128 continue;
1130 $to = trim( $v[1] );
1131 $v = trim( $v[0] );
1132 $u = explode( '=>', $v, 2 );
1133 // if $to is empty, strtr() could return a wrong result
1134 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1135 $bidtable[$v] = $to;
1136 } elseif ( count( $u ) == 2 ) {
1137 $from = trim( $u[0] );
1138 $v = trim( $u[1] );
1139 if ( array_key_exists( $v, $unidtable )
1140 && !is_array( $unidtable[$v] )
1141 && $to
1142 && in_array( $v, $variants ) ) {
1143 $unidtable[$v] = array( $from => $to );
1144 } elseif ( $to && in_array( $v, $variants ) ) {
1145 $unidtable[$v][$from] = $to;
1148 // syntax error, pass
1149 if ( !isset( $this->mConverter->mVariantNames[$v] ) ) {
1150 $bidtable = array();
1151 $unidtable = array();
1152 break;
1155 $this->mBidtable = $bidtable;
1156 $this->mUnidtable = $unidtable;
1160 * @private
1162 function getRulesDesc() {
1163 $codesep = $this->mConverter->mDescCodeSep;
1164 $varsep = $this->mConverter->mDescVarSep;
1165 $text = '';
1166 foreach ( $this->mBidtable as $k => $v ) {
1167 $text .= $this->mConverter->mVariantNames[$k] . "$codesep$v$varsep";
1169 foreach ( $this->mUnidtable as $k => $a ) {
1170 foreach ( $a as $from => $to ) {
1171 $text .= $from . '⇒' . $this->mConverter->mVariantNames[$k] .
1172 "$codesep$to$varsep";
1175 return $text;
1179 * Parse rules conversion.
1180 * @private
1182 function getRuleConvertedStr( $variant ) {
1183 $bidtable = $this->mBidtable;
1184 $unidtable = $this->mUnidtable;
1186 if ( count( $bidtable ) + count( $unidtable ) == 0 ) {
1187 return $this->mRules;
1188 } else {
1189 // display current variant in bidirectional array
1190 $disp = $this->getTextInBidtable( $variant );
1191 // or display current variant in fallbacks
1192 if ( !$disp ) {
1193 $disp = $this->getTextInBidtable(
1194 $this->mConverter->getVariantFallbacks( $variant ) );
1196 // or display current variant in unidirectional array
1197 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1198 $disp = array_values( $unidtable[$variant] );
1199 $disp = $disp[0];
1201 // or display frist text under disable manual convert
1202 if ( !$disp
1203 && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
1204 if ( count( $bidtable ) > 0 ) {
1205 $disp = array_values( $bidtable );
1206 $disp = $disp[0];
1207 } else {
1208 $disp = array_values( $unidtable );
1209 $disp = array_values( $disp[0] );
1210 $disp = $disp[0];
1213 return $disp;
1218 * Generate conversion table for all text.
1219 * @private
1221 function generateConvTable() {
1222 // Special case optimisation
1223 if ( !$this->mBidtable && !$this->mUnidtable ) {
1224 $this->mConvTable = array();
1225 return;
1228 $bidtable = $this->mBidtable;
1229 $unidtable = $this->mUnidtable;
1230 $manLevel = $this->mConverter->mManualLevel;
1232 $vmarked = array();
1233 foreach ( $this->mConverter->mVariants as $v ) {
1234 /* for bidirectional array
1235 fill in the missing variants, if any,
1236 with fallbacks */
1237 if ( !isset( $bidtable[$v] ) ) {
1238 $variantFallbacks =
1239 $this->mConverter->getVariantFallbacks( $v );
1240 $vf = $this->getTextInBidtable( $variantFallbacks );
1241 if ( $vf ) {
1242 $bidtable[$v] = $vf;
1246 if ( isset( $bidtable[$v] ) ) {
1247 foreach ( $vmarked as $vo ) {
1248 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1249 // or -{H|zh:WordZh;zh-tw:WordTw}-
1250 // or -{-|zh:WordZh;zh-tw:WordTw}-
1251 // to introduce a custom mapping between
1252 // words WordZh and WordTw in the whole text
1253 if ( $manLevel[$v] == 'bidirectional' ) {
1254 $this->mConvTable[$v][$bidtable[$vo]] = $bidtable[$v];
1256 if ( $manLevel[$vo] == 'bidirectional' ) {
1257 $this->mConvTable[$vo][$bidtable[$v]] = $bidtable[$vo];
1260 $vmarked[] = $v;
1262 /*for unidirectional array fill to convert tables */
1263 if ( ( $manLevel[$v] == 'bidirectional' || $manLevel[$v] == 'unidirectional' )
1264 && isset( $unidtable[$v] ) )
1266 if ( isset( $this->mConvTable[$v] ) ) {
1267 $this->mConvTable[$v] = array_merge( $this->mConvTable[$v], $unidtable[$v] );
1268 } else {
1269 $this->mConvTable[$v] = $unidtable[$v];
1276 * Parse rules and flags.
1277 * @public
1279 function parse( $variant = NULL ) {
1280 if ( !$variant ) {
1281 $variant = $this->mConverter->getPreferredVariant();
1284 $variants = $this->mConverter->mVariants;
1285 $this->parseFlags();
1286 $flags = $this->mFlags;
1288 // convert to specified variant
1289 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1290 if ( $this->mVariantFlags ) {
1291 // check if current variant in flags
1292 if ( isset( $this->mVariantFlags[$variant] ) ) {
1293 // then convert <text to convert> to current language
1294 $this->mRules = $this->mConverter->autoConvert( $this->mRules,
1295 $variant );
1296 } else { // if current variant no in flags,
1297 // then we check its fallback variants.
1298 $variantFallbacks =
1299 $this->mConverter->getVariantFallbacks( $variant );
1300 foreach ( $variantFallbacks as $variantFallback ) {
1301 // if current variant's fallback exist in flags
1302 if ( isset( $this->mVariantFlags[$variantFallback] ) ) {
1303 // then convert <text to convert> to fallback language
1304 $this->mRules =
1305 $this->mConverter->autoConvert( $this->mRules,
1306 $variantFallback );
1307 break;
1311 $this->mFlags = $flags = array( 'R' => true );
1314 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1315 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1316 $this->mRules = str_replace( '=&gt;', '=>', $this->mRules );
1317 $this->parseRules();
1319 $rules = $this->mRules;
1321 if ( !$this->mBidtable && !$this->mUnidtable ) {
1322 if ( isset( $flags['+'] ) || isset( $flags['-'] ) ) {
1323 // fill all variants if text in -{A/H/-|text} without rules
1324 foreach ( $this->mConverter->mVariants as $v ) {
1325 $this->mBidtable[$v] = $rules;
1327 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1328 $this->mFlags = $flags = array( 'R' => true );
1332 $this->mRuleDisplay = false;
1333 foreach ( $flags as $flag => $unused ) {
1334 switch ( $flag ) {
1335 case 'R':
1336 // if we don't do content convert, still strip the -{}- tags
1337 $this->mRuleDisplay = $rules;
1338 break;
1339 case 'N':
1340 // process N flag: output current variant name
1341 $ruleVar = trim( $rules );
1342 if ( isset( $this->mConverter->mVariantNames[$ruleVar] ) ) {
1343 $this->mRuleDisplay = $this->mConverter->mVariantNames[$ruleVar];
1344 } else {
1345 $this->mRuleDisplay = '';
1347 break;
1348 case 'D':
1349 // process D flag: output rules description
1350 $this->mRuleDisplay = $this->getRulesDesc();
1351 break;
1352 case 'H':
1353 // process H,- flag or T only: output nothing
1354 $this->mRuleDisplay = '';
1355 break;
1356 case '-':
1357 $this->mRulesAction = 'remove';
1358 $this->mRuleDisplay = '';
1359 break;
1360 case '+':
1361 $this->mRulesAction = 'add';
1362 $this->mRuleDisplay = '';
1363 break;
1364 case 'S':
1365 $this->mRuleDisplay = $this->getRuleConvertedStr( $variant );
1366 break;
1367 case 'T':
1368 $this->mRuleTitle = $this->getRuleConvertedStr( $variant );
1369 $this->mRuleDisplay = '';
1370 break;
1371 default:
1372 // ignore unknown flags (but see error case below)
1375 if ( $this->mRuleDisplay === false ) {
1376 $this->mRuleDisplay = $this->mManualCodeError;
1379 $this->generateConvTable();
1383 * @public
1385 function hasRules() {
1386 // TODO:
1390 * Get display text on markup -{...}-
1391 * @public
1393 function getDisplay() {
1394 return $this->mRuleDisplay;
1398 * Get converted title.
1399 * @public
1401 function getTitle() {
1402 return $this->mRuleTitle;
1406 * Return how deal with conversion rules.
1407 * @public
1409 function getRulesAction() {
1410 return $this->mRulesAction;
1414 * Get conversion table. ( bidirectional and unidirectional
1415 * conversion table )
1416 * @public
1418 function getConvTable() {
1419 return $this->mConvTable;
1423 * Get conversion rules string.
1424 * @public
1426 function getRules() {
1427 return $this->mRules;
1431 * Get conversion flags.
1432 * @public
1434 function getFlags() {
1435 return $this->mFlags;