Fixed spacing in actions/cache/filebackend/filerepo/job folder
[mediawiki.git] / languages / LanguageConverter.php
blob512736b59439fe3b5dd28b7935bf068d90e2af80
1 <?php
2 /**
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
20 * @file
21 * @ingroup Language
24 /**
25 * Base class for language conversion.
26 * @ingroup Language
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 {
33 /**
34 * languages supporting variants
35 * @since 1.20
36 * @var array
38 static public $languagesWithVariants = array(
39 'gan',
40 'iu',
41 'kk',
42 'ku',
43 'shi',
44 'sr',
45 'tg',
46 'uz',
47 'zh',
50 public $mMainLanguageCode;
51 public $mVariants, $mVariantFallbacks, $mVariantNames;
52 public $mTablesLoaded = false;
53 public $mTables;
54 // 'bidirectional' 'unidirectional' 'disable' for each variant
55 public $mManualLevel;
57 /**
58 * @var String: memcached key name
60 public $mCacheKey;
62 public $mLangObj;
63 public $mFlags;
64 public $mDescCodeSep = ':', $mDescVarSep = ';';
65 public $mUcfirst = false;
66 public $mConvRuleTitle = false;
67 public $mURLVariant;
68 public $mUserVariant;
69 public $mHeaderVariant;
70 public $mMaxDepth = 10;
71 public $mVarSeparatorPattern;
73 const CACHE_VERSION_KEY = 'VERSION 6';
75 /**
76 * Constructor
78 * @param $langobj Language: the Language Object
79 * @param $maincode String: the main language code of this language
80 * @param $variants Array: the supported variants of this language
81 * @param $variantfallbacks Array: the fallback language of each variant
82 * @param $flags Array: defining the custom strings that maps to the flags
83 * @param $manualLevel Array: limit for supported variants
85 public function __construct( $langobj, $maincode, $variants = array(),
86 $variantfallbacks = array(), $flags = array(),
87 $manualLevel = array() ) {
88 global $wgDisabledVariants;
89 $this->mLangObj = $langobj;
90 $this->mMainLanguageCode = $maincode;
91 $this->mVariants = array_diff( $variants, $wgDisabledVariants );
92 $this->mVariantFallbacks = $variantfallbacks;
93 $this->mVariantNames = Language::fetchLanguageNames();
94 $this->mCacheKey = wfMemcKey( 'conversiontables', $maincode );
95 $defaultflags = array(
96 // 'S' show converted text
97 // '+' add rules for alltext
98 // 'E' the gave flags is error
99 // these flags above are reserved for program
100 'A' => 'A', // add rule for convert code (all text convert)
101 'T' => 'T', // title convert
102 'R' => 'R', // raw content
103 'D' => 'D', // convert description (subclass implement)
104 '-' => '-', // remove convert (not implement)
105 'H' => 'H', // add rule for convert code
106 // (but no display in placed code)
107 'N' => 'N' // current variant name
109 $this->mFlags = array_merge( $defaultflags, $flags );
110 foreach ( $this->mVariants as $v ) {
111 if ( array_key_exists( $v, $manualLevel ) ) {
112 $this->mManualLevel[$v] = $manualLevel[$v];
113 } else {
114 $this->mManualLevel[$v] = 'bidirectional';
116 $this->mFlags[$v] = $v;
121 * Get all valid variants.
122 * Call this instead of using $this->mVariants directly.
124 * @return Array: contains all valid variants
126 public function getVariants() {
127 return $this->mVariants;
131 * In case some variant is not defined in the markup, we need
132 * to have some fallback. For example, in zh, normally people
133 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
134 * when zh-sg is preferred but not defined, we will pick zh-hans
135 * in this case. Right now this is only used by zh.
137 * @param $variant String: the language code of the variant
138 * @return String|array: The code of the fallback language or the
139 * main code if there is no fallback
141 public function getVariantFallbacks( $variant ) {
142 if ( isset( $this->mVariantFallbacks[$variant] ) ) {
143 return $this->mVariantFallbacks[$variant];
145 return $this->mMainLanguageCode;
149 * Get the title produced by the conversion rule.
150 * @return String: The converted title text
152 public function getConvRuleTitle() {
153 return $this->mConvRuleTitle;
157 * Get preferred language variant.
158 * @return String: the preferred language code
160 public function getPreferredVariant() {
161 global $wgDefaultLanguageVariant, $wgUser;
163 $req = $this->getURLVariant();
165 if ( $wgUser->isLoggedIn() && !$req ) {
166 $req = $this->getUserVariant();
167 } elseif ( !$req ) {
168 $req = $this->getHeaderVariant();
171 if ( $wgDefaultLanguageVariant && !$req ) {
172 $req = $this->validateVariant( $wgDefaultLanguageVariant );
175 // This function, unlike the other get*Variant functions, is
176 // not memoized (i.e. there return value is not cached) since
177 // new information might appear during processing after this
178 // is first called.
179 if ( $this->validateVariant( $req ) ) {
180 return $req;
182 return $this->mMainLanguageCode;
186 * Get default variant.
187 * This function would not be affected by user's settings
188 * @return String: the default variant code
190 public function getDefaultVariant() {
191 global $wgDefaultLanguageVariant;
193 $req = $this->getURLVariant();
195 if ( !$req ) {
196 $req = $this->getHeaderVariant();
199 if ( $wgDefaultLanguageVariant && !$req ) {
200 $req = $this->validateVariant( $wgDefaultLanguageVariant );
203 if ( $req ) {
204 return $req;
206 return $this->mMainLanguageCode;
210 * Validate the variant
211 * @param $variant String: the variant to validate
212 * @return Mixed: returns the variant if it is valid, null otherwise
214 public function validateVariant( $variant = null ) {
215 if ( $variant !== null && in_array( $variant, $this->mVariants ) ) {
216 return $variant;
218 return null;
222 * Get the variant specified in the URL
224 * @return Mixed: variant if one found, false otherwise.
226 public function getURLVariant() {
227 global $wgRequest;
229 if ( $this->mURLVariant ) {
230 return $this->mURLVariant;
233 // see if the preference is set in the request
234 $ret = $wgRequest->getText( 'variant' );
236 if ( !$ret ) {
237 $ret = $wgRequest->getVal( 'uselang' );
240 return $this->mURLVariant = $this->validateVariant( $ret );
244 * Determine if the user has a variant set.
246 * @return Mixed: variant if one found, false otherwise.
248 protected function getUserVariant() {
249 global $wgUser;
251 // memoizing this function wreaks havoc on parserTest.php
253 if ( $this->mUserVariant ) {
254 return $this->mUserVariant;
258 // Get language variant preference from logged in users
259 // Don't call this on stub objects because that causes infinite
260 // recursion during initialisation
261 if ( $wgUser->isLoggedIn() ) {
262 $ret = $wgUser->getOption( 'variant' );
263 } else {
264 // figure out user lang without constructing wgLang to avoid
265 // infinite recursion
266 $ret = $wgUser->getOption( 'language' );
269 return $this->mUserVariant = $this->validateVariant( $ret );
273 * Determine the language variant from the Accept-Language header.
275 * @return Mixed: variant if one found, false otherwise.
277 protected function getHeaderVariant() {
278 global $wgRequest;
280 if ( $this->mHeaderVariant ) {
281 return $this->mHeaderVariant;
284 // see if some supported language variant is set in the
285 // HTTP header.
286 $languages = array_keys( $wgRequest->getAcceptLang() );
287 if ( empty( $languages ) ) {
288 return null;
291 $fallbackLanguages = array();
292 foreach ( $languages as $language ) {
293 $this->mHeaderVariant = $this->validateVariant( $language );
294 if ( $this->mHeaderVariant ) {
295 break;
298 // To see if there are fallbacks of current language.
299 // We record these fallback variants, and process
300 // them later.
301 $fallbacks = $this->getVariantFallbacks( $language );
302 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode ) {
303 $fallbackLanguages[] = $fallbacks;
304 } elseif ( is_array( $fallbacks ) ) {
305 $fallbackLanguages =
306 array_merge( $fallbackLanguages, $fallbacks );
310 if ( !$this->mHeaderVariant ) {
311 // process fallback languages now
312 $fallback_languages = array_unique( $fallbackLanguages );
313 foreach ( $fallback_languages as $language ) {
314 $this->mHeaderVariant = $this->validateVariant( $language );
315 if ( $this->mHeaderVariant ) {
316 break;
321 return $this->mHeaderVariant;
325 * Dictionary-based conversion.
326 * This function would not parse the conversion rules.
327 * If you want to parse rules, try to use convert() or
328 * convertTo().
330 * @param $text String the text to be converted
331 * @param $toVariant bool|string the target language code
332 * @return String the converted text
334 public function autoConvert( $text, $toVariant = false ) {
335 wfProfileIn( __METHOD__ );
337 $this->loadTables();
339 if ( !$toVariant ) {
340 $toVariant = $this->getPreferredVariant();
341 if ( !$toVariant ) {
342 wfProfileOut( __METHOD__ );
343 return $text;
347 if ( $this->guessVariant( $text, $toVariant ) ) {
348 wfProfileOut( __METHOD__ );
349 return $text;
352 /* we convert everything except:
353 1. HTML markups (anything between < and >)
354 2. HTML entities
355 3. placeholders created by the parser
357 global $wgParser;
358 if ( isset( $wgParser ) && $wgParser->UniqPrefix() != '' ) {
359 $marker = '|' . $wgParser->UniqPrefix() . '[\-a-zA-Z0-9]+';
360 } else {
361 $marker = '';
364 // this one is needed when the text is inside an HTML markup
365 $htmlfix = '|<[^>]+$|^[^<>]*>';
367 // disable convert to variants between <code></code> tags
368 $codefix = '<code>.+?<\/code>|';
369 // disable convertsion of <script type="text/javascript"> ... </script>
370 $scriptfix = '<script.*?>.*?<\/script>|';
371 // disable conversion of <pre xxxx> ... </pre>
372 $prefix = '<pre.*?>.*?<\/pre>|';
374 $reg = '/' . $codefix . $scriptfix . $prefix .
375 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
376 $startPos = 0;
377 $sourceBlob = '';
378 $literalBlob = '';
380 // Guard against delimiter nulls in the input
381 $text = str_replace( "\000", '', $text );
383 $markupMatches = null;
384 $elementMatches = null;
385 while ( $startPos < strlen( $text ) ) {
386 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
387 $elementPos = $markupMatches[0][1];
388 $element = $markupMatches[0][0];
389 } else {
390 $elementPos = strlen( $text );
391 $element = '';
394 // Queue the part before the markup for translation in a batch
395 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
397 // Advance to the next position
398 $startPos = $elementPos + strlen( $element );
400 // Translate any alt or title attributes inside the matched element
401 if ( $element !== '' && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element,
402 $elementMatches ) )
404 $attrs = Sanitizer::decodeTagAttributes( $elementMatches[2] );
405 $changed = false;
406 foreach ( array( 'title', 'alt' ) as $attrName ) {
407 if ( !isset( $attrs[$attrName] ) ) {
408 continue;
410 $attr = $attrs[$attrName];
411 // Don't convert URLs
412 if ( !strpos( $attr, '://' ) ) {
413 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
416 // Remove HTML tags to avoid disrupting the layout
417 $attr = preg_replace( '/<[^>]+>/', '', $attr );
418 if ( $attr !== $attrs[$attrName] ) {
419 $attrs[$attrName] = $attr;
420 $changed = true;
423 if ( $changed ) {
424 $element = $elementMatches[1] . Html::expandAttributes( $attrs ) .
425 $elementMatches[3];
428 $literalBlob .= $element . "\000";
431 // Do the main translation batch
432 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
434 // Put the output back together
435 $translatedIter = StringUtils::explode( "\000", $translatedBlob );
436 $literalIter = StringUtils::explode( "\000", $literalBlob );
437 $output = '';
438 while ( $translatedIter->valid() && $literalIter->valid() ) {
439 $output .= $translatedIter->current();
440 $output .= $literalIter->current();
441 $translatedIter->next();
442 $literalIter->next();
445 wfProfileOut( __METHOD__ );
446 return $output;
450 * Translate a string to a variant.
451 * Doesn't parse rules or do any of that other stuff, for that use
452 * convert() or convertTo().
454 * @param $text String: text to convert
455 * @param $variant String: variant language code
456 * @return String: translated text
458 public function translate( $text, $variant ) {
459 wfProfileIn( __METHOD__ );
460 // If $text is empty or only includes spaces, do nothing
461 // Otherwise translate it
462 if ( trim( $text ) ) {
463 $this->loadTables();
464 $text = $this->mTables[$variant]->replace( $text );
466 wfProfileOut( __METHOD__ );
467 return $text;
471 * Call translate() to convert text to all valid variants.
473 * @param $text String: the text to be converted
474 * @return Array: variant => converted text
476 public function autoConvertToAllVariants( $text ) {
477 wfProfileIn( __METHOD__ );
478 $this->loadTables();
480 $ret = array();
481 foreach ( $this->mVariants as $variant ) {
482 $ret[$variant] = $this->translate( $text, $variant );
485 wfProfileOut( __METHOD__ );
486 return $ret;
490 * Convert link text to all valid variants.
491 * In the first, this function only convert text outside the
492 * "-{" "}-" markups. Since the "{" and "}" are not allowed in
493 * titles, the text will get all converted always.
494 * So I removed this feature and deprecated the function.
496 * @param $text String: the text to be converted
497 * @return Array: variant => converted text
498 * @deprecated since 1.17 Use autoConvertToAllVariants() instead
500 public function convertLinkToAllVariants( $text ) {
501 return $this->autoConvertToAllVariants( $text );
505 * Apply manual conversion rules.
507 * @param $convRule ConverterRule Object of ConverterRule
509 protected function applyManualConv( $convRule ) {
510 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
511 // title conversion.
512 // Bug 24072: $mConvRuleTitle was overwritten by other manual
513 // rule(s) not for title, this breaks the title conversion.
514 $newConvRuleTitle = $convRule->getTitle();
515 if ( $newConvRuleTitle ) {
516 // So I add an empty check for getTitle()
517 $this->mConvRuleTitle = $newConvRuleTitle;
520 // merge/remove manual conversion rules to/from global table
521 $convTable = $convRule->getConvTable();
522 $action = $convRule->getRulesAction();
523 foreach ( $convTable as $variant => $pair ) {
524 if ( !$this->validateVariant( $variant ) ) {
525 continue;
528 if ( $action == 'add' ) {
529 foreach ( $pair as $from => $to ) {
530 // to ensure that $from and $to not be left blank
531 // so $this->translate() could always return a string
532 if ( $from || $to ) {
533 // more efficient than array_merge(), about 2.5 times.
534 $this->mTables[$variant]->setPair( $from, $to );
537 } elseif ( $action == 'remove' ) {
538 $this->mTables[$variant]->removeArray( $pair );
544 * Auto convert a Title object to a readable string in the
545 * preferred variant.
547 * @param $title Title a object of Title
548 * @return String: converted title text
550 public function convertTitle( $title ) {
551 $variant = $this->getPreferredVariant();
552 $index = $title->getNamespace();
553 if ( $index !== NS_MAIN ) {
554 $text = $this->convertNamespace( $index ) . ':';
555 } else {
556 $text = '';
558 $text .= $this->translate( $title->getText(), $variant );
559 return $text;
563 * Get the namespace display name in the preferred variant.
565 * @param $index int namespace id
566 * @return String: namespace name for display
568 public function convertNamespace( $index ) {
569 $variant = $this->getPreferredVariant();
570 if ( $index === NS_MAIN ) {
571 return '';
572 } else {
573 // First check if a message gives a converted name in the target variant.
574 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
575 if ( $nsConvMsg->exists() ) {
576 return $nsConvMsg->plain();
578 // Then check if a message gives a converted name in content language
579 // which needs extra translation to the target variant.
580 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
581 if ( $nsConvMsg->exists() ) {
582 return $this->translate( $nsConvMsg->plain(), $variant );
584 // No message exists, retrieve it from the target variant's namespace names.
585 $langObj = $this->mLangObj->factory( $variant );
586 return $langObj->getFormattedNsText( $index );
591 * Convert text to different variants of a language. The automatic
592 * conversion is done in autoConvert(). Here we parse the text
593 * marked with -{}-, which specifies special conversions of the
594 * text that can not be accomplished in autoConvert().
596 * Syntax of the markup:
597 * -{code1:text1;code2:text2;...}- or
598 * -{flags|code1:text1;code2:text2;...}- or
599 * -{text}- in which case no conversion should take place for text
601 * @param $text String: text to be converted
602 * @return String: converted text
604 public function convert( $text ) {
605 $variant = $this->getPreferredVariant();
606 return $this->convertTo( $text, $variant );
610 * Same as convert() except a extra parameter to custom variant.
612 * @param $text String: text to be converted
613 * @param $variant String: the target variant code
614 * @return String: converted text
616 public function convertTo( $text, $variant ) {
617 global $wgDisableLangConversion;
618 if ( $wgDisableLangConversion ) {
619 return $text;
621 // Reset converter state for a new converter run.
622 $this->mConvRuleTitle = false;
623 return $this->recursiveConvertTopLevel( $text, $variant );
627 * Recursively convert text on the outside. Allow to use nested
628 * markups to custom rules.
630 * @param $text String: text to be converted
631 * @param $variant String: the target variant code
632 * @param $depth Integer: depth of recursion
633 * @return String: converted text
635 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
636 $startPos = 0;
637 $out = '';
638 $length = strlen( $text );
639 $shouldConvert = !$this->guessVariant( $text, $variant );
641 while ( $startPos < $length ) {
642 $pos = strpos( $text, '-{', $startPos );
644 if ( $pos === false ) {
645 // No more markup, append final segment
646 $fragment = substr( $text, $startPos );
647 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
648 return $out;
651 // Markup found
652 // Append initial segment
653 $fragment = substr( $text, $startPos, $pos - $startPos );
654 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
656 // Advance position
657 $startPos = $pos;
659 // Do recursive conversion
660 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
663 return $out;
667 * Recursively convert text on the inside.
669 * @param $text String: text to be converted
670 * @param $variant String: the target variant code
671 * @param $startPos int
672 * @param $depth Integer: depth of recursion
674 * @throws MWException
675 * @return String: converted text
677 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
678 // Quick sanity check (no function calls)
679 if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
680 throw new MWException( __METHOD__ . ': invalid input string' );
683 $startPos += 2;
684 $inner = '';
685 $warningDone = false;
686 $length = strlen( $text );
688 while ( $startPos < $length ) {
689 $m = false;
690 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
691 if ( !$m ) {
692 // Unclosed rule
693 break;
696 $token = $m[0][0];
697 $pos = $m[0][1];
699 // Markup found
700 // Append initial segment
701 $inner .= substr( $text, $startPos, $pos - $startPos );
703 // Advance position
704 $startPos = $pos;
706 switch ( $token ) {
707 case '-{':
708 // Check max depth
709 if ( $depth >= $this->mMaxDepth ) {
710 $inner .= '-{';
711 if ( !$warningDone ) {
712 $inner .= '<span class="error">' .
713 wfMessage( 'language-converter-depth-warning' )
714 ->numParams( $this->mMaxDepth )->inContentLanguage()->text() .
715 '</span>';
716 $warningDone = true;
718 $startPos += 2;
719 continue;
721 // Recursively parse another rule
722 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
723 break;
724 case '}-':
725 // Apply the rule
726 $startPos += 2;
727 $rule = new ConverterRule( $inner, $this );
728 $rule->parse( $variant );
729 $this->applyManualConv( $rule );
730 return $rule->getDisplay();
731 default:
732 throw new MWException( __METHOD__ . ': invalid regex match' );
736 // Unclosed rule
737 if ( $startPos < $length ) {
738 $inner .= substr( $text, $startPos );
740 $startPos = $length;
741 return '-{' . $this->autoConvert( $inner, $variant );
745 * If a language supports multiple variants, it is possible that
746 * non-existing link in one variant actually exists in another variant.
747 * This function tries to find it. See e.g. LanguageZh.php
749 * @param $link String: the name of the link
750 * @param $nt Mixed: the title object of the link
751 * @param $ignoreOtherCond Boolean: to disable other conditions when
752 * we need to transclude a template or update a category's link
753 * @return Null, the input parameters may be modified upon return
755 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
756 # If the article has already existed, there is no need to
757 # check it again, otherwise it may cause a fault.
758 if ( is_object( $nt ) && $nt->exists() ) {
759 return;
762 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest,
763 $wgUser;
764 $isredir = $wgRequest->getText( 'redirect', 'yes' );
765 $action = $wgRequest->getText( 'action' );
766 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
767 $disableLinkConversion = $wgDisableLangConversion
768 || $wgDisableTitleConversion;
769 $linkBatch = new LinkBatch();
771 $ns = NS_MAIN;
773 if ( $disableLinkConversion ||
774 ( !$ignoreOtherCond &&
775 ( $isredir == 'no'
776 || $action == 'edit'
777 || $action == 'submit'
778 || $linkconvert == 'no'
779 || $wgUser->getOption( 'noconvertlink' ) == 1 ) ) ) {
780 return;
783 if ( is_object( $nt ) ) {
784 $ns = $nt->getNamespace();
787 $variants = $this->autoConvertToAllVariants( $link );
788 if ( !$variants ) { // give up
789 return;
792 $titles = array();
794 foreach ( $variants as $v ) {
795 if ( $v != $link ) {
796 $varnt = Title::newFromText( $v, $ns );
797 if ( !is_null( $varnt ) ) {
798 $linkBatch->addObj( $varnt );
799 $titles[] = $varnt;
804 // fetch all variants in single query
805 $linkBatch->execute();
807 foreach ( $titles as $varnt ) {
808 if ( $varnt->getArticleID() > 0 ) {
809 $nt = $varnt;
810 $link = $varnt->getText();
811 break;
817 * Returns language specific hash options.
819 * @return string
821 public function getExtraHashOptions() {
822 $variant = $this->getPreferredVariant();
823 return '!' . $variant;
827 * Guess if a text is written in a variant. This should be implemented in subclasses.
829 * @param string $text the text to be checked
830 * @param string $variant language code of the variant to be checked for
831 * @return bool true if $text appears to be written in $variant, false if not
833 * @author Nikola Smolenski <smolensk@eunet.rs>
834 * @since 1.19
836 public function guessVariant($text, $variant) {
837 return false;
841 * Load default conversion tables.
842 * This method must be implemented in derived class.
844 * @private
845 * @throws MWException
847 function loadDefaultTables() {
848 $name = get_class( $this );
849 throw new MWException( "Must implement loadDefaultTables() method in class $name" );
853 * Load conversion tables either from the cache or the disk.
854 * @private
855 * @param $fromCache Boolean: load from memcached? Defaults to true.
857 function loadTables( $fromCache = true ) {
858 global $wgLangConvMemc;
860 if ( $this->mTablesLoaded ) {
861 return;
864 wfProfileIn( __METHOD__ );
865 $this->mTablesLoaded = true;
866 $this->mTables = false;
867 if ( $fromCache ) {
868 wfProfileIn( __METHOD__ . '-cache' );
869 $this->mTables = $wgLangConvMemc->get( $this->mCacheKey );
870 wfProfileOut( __METHOD__ . '-cache' );
872 if ( !$this->mTables
873 || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
874 wfProfileIn( __METHOD__ . '-recache' );
875 // not in cache, or we need a fresh reload.
876 // We will first load the default tables
877 // then update them using things in MediaWiki:Conversiontable/*
878 $this->loadDefaultTables();
879 foreach ( $this->mVariants as $var ) {
880 $cached = $this->parseCachedTable( $var );
881 $this->mTables[$var]->mergeArray( $cached );
884 $this->postLoadTables();
885 $this->mTables[self::CACHE_VERSION_KEY] = true;
887 $wgLangConvMemc->set( $this->mCacheKey, $this->mTables, 43200 );
888 wfProfileOut( __METHOD__ . '-recache' );
890 wfProfileOut( __METHOD__ );
894 * Hook for post processing after conversion tables are loaded.
896 function postLoadTables() { }
899 * Reload the conversion tables.
901 * @private
903 function reloadTables() {
904 if ( $this->mTables ) {
905 unset( $this->mTables );
907 $this->mTablesLoaded = false;
908 $this->loadTables( false );
912 * Parse the conversion table stored in the cache.
914 * The tables should be in blocks of the following form:
915 * -{
916 * word => word ;
917 * word => word ;
918 * ...
919 * }-
921 * To make the tables more manageable, subpages are allowed
922 * and will be parsed recursively if $recursive == true.
924 * @param $code String: language code
925 * @param $subpage String: subpage name
926 * @param $recursive Boolean: parse subpages recursively? Defaults to true.
928 * @return array
930 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
931 static $parsed = array();
933 $key = 'Conversiontable/' . $code;
934 if ( $subpage ) {
935 $key .= '/' . $subpage;
937 if ( array_key_exists( $key, $parsed ) ) {
938 return array();
941 $parsed[$key] = true;
943 if ( $subpage === '' ) {
944 $txt = MessageCache::singleton()->getMsgFromNamespace( $key, $code );
945 } else {
946 $txt = false;
947 $title = Title::makeTitleSafe( NS_MEDIAWIKI, $key );
948 if ( $title && $title->exists() ) {
949 $revision = Revision::newFromTitle( $title );
950 if ( $revision ) {
951 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT ) {
952 $txt = $revision->getContent( Revision::RAW )->getNativeData();
955 //@todo: in the future, use a specialized content model, perhaps based on json!
960 # Nothing to parse if there's no text
961 if ( $txt === false || $txt === null || $txt === '' ) {
962 return array();
965 // get all subpage links of the form
966 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
967 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
968 ':Conversiontable';
969 $subs = StringUtils::explode( '[[', $txt );
970 $sublinks = array();
971 foreach ( $subs as $sub ) {
972 $link = explode( ']]', $sub, 2 );
973 if ( count( $link ) != 2 ) {
974 continue;
976 $b = explode( '|', $link[0], 2 );
977 $b = explode( '/', trim( $b[0] ), 3 );
978 if ( count( $b ) == 3 ) {
979 $sublink = $b[2];
980 } else {
981 $sublink = '';
984 if ( $b[0] == $linkhead && $b[1] == $code ) {
985 $sublinks[] = $sublink;
989 // parse the mappings in this page
990 $blocks = StringUtils::explode( '-{', $txt );
991 $ret = array();
992 $first = true;
993 foreach ( $blocks as $block ) {
994 if ( $first ) {
995 // Skip the part before the first -{
996 $first = false;
997 continue;
999 $mappings = explode( '}-', $block, 2 );
1000 $stripped = str_replace( array( "'", '"', '*', '#' ), '',
1001 $mappings[0] );
1002 $table = StringUtils::explode( ';', $stripped );
1003 foreach ( $table as $t ) {
1004 $m = explode( '=>', $t, 3 );
1005 if ( count( $m ) != 2 ) {
1006 continue;
1008 // trim any trailling comments starting with '//'
1009 $tt = explode( '//', $m[1], 2 );
1010 $ret[trim( $m[0] )] = trim( $tt[0] );
1014 // recursively parse the subpages
1015 if ( $recursive ) {
1016 foreach ( $sublinks as $link ) {
1017 $s = $this->parseCachedTable( $code, $link, $recursive );
1018 $ret = array_merge( $ret, $s );
1022 if ( $this->mUcfirst ) {
1023 foreach ( $ret as $k => $v ) {
1024 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
1027 return $ret;
1031 * Enclose a string with the "no conversion" tag. This is used by
1032 * various functions in the Parser.
1034 * @param $text String: text to be tagged for no conversion
1035 * @param $noParse Boolean: unused
1036 * @return String: the tagged text
1038 public function markNoConversion( $text, $noParse = false ) {
1039 # don't mark if already marked
1040 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
1041 return $text;
1044 $ret = "-{R|$text}-";
1045 return $ret;
1049 * Convert the sorting key for category links. This should make different
1050 * keys that are variants of each other map to the same key.
1052 * @param $key string
1054 * @return string
1056 function convertCategoryKey( $key ) {
1057 return $key;
1061 * Hook to refresh the cache of conversion tables when
1062 * MediaWiki:Conversiontable* is updated.
1063 * @private
1065 * @param $page WikiPage object
1066 * @param $user Object: User object for the current user
1067 * @param $content Content: new page content
1068 * @param $summary String: edit summary of the edit
1069 * @param $isMinor Boolean: was the edit marked as minor?
1070 * @param $isWatch Boolean: did the user watch this page or not?
1071 * @param $section
1072 * @param $flags int Bitfield
1073 * @param $revision Object: new Revision object or null
1074 * @return Boolean: true
1076 function OnPageContentSaveComplete( $page, $user, $content, $summary, $isMinor,
1077 $isWatch, $section, $flags, $revision ) {
1078 $titleobj = $page->getTitle();
1079 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
1080 $title = $titleobj->getDBkey();
1081 $t = explode( '/', $title, 3 );
1082 $c = count( $t );
1083 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1084 if ( $this->validateVariant( $t[1] ) ) {
1085 $this->reloadTables();
1089 return true;
1093 * Armour rendered math against conversion.
1094 * Escape special chars in parsed math text. (in most cases are img elements)
1096 * @param $text String: text to armour against conversion
1097 * @return String: armoured text where { and } have been converted to
1098 * &#123; and &#125;
1100 public function armourMath( $text ) {
1101 // convert '-{' and '}-' to '-&#123;' and '&#125;-' to prevent
1102 // any unwanted markup appearing in the math image tag.
1103 $text = strtr( $text, array( '-{' => '-&#123;', '}-' => '&#125;-' ) );
1104 return $text;
1108 * Get the cached separator pattern for ConverterRule::parseRules()
1110 function getVarSeparatorPattern() {
1111 if ( is_null( $this->mVarSeparatorPattern ) ) {
1112 // varsep_pattern for preg_split:
1113 // text should be splited by ";" only if a valid variant
1114 // name exist after the markup, for example:
1115 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1116 // <span style="font-size:120%;">yyy</span>;}-
1117 // we should split it as:
1118 // array(
1119 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1120 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1121 // [2] => ''
1122 // )
1123 $pat = '/;\s*(?=';
1124 foreach ( $this->mVariants as $variant ) {
1125 // zh-hans:xxx;zh-hant:yyy
1126 $pat .= $variant . '\s*:|';
1127 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1128 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1130 $pat .= '\s*$)/';
1131 $this->mVarSeparatorPattern = $pat;
1133 return $this->mVarSeparatorPattern;
1138 * Parser for rules of language conversion , parse rules in -{ }- tag.
1139 * @ingroup Language
1140 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
1142 class ConverterRule {
1143 public $mText; // original text in -{text}-
1144 public $mConverter; // LanguageConverter object
1145 public $mRuleDisplay = '';
1146 public $mRuleTitle = false;
1147 public $mRules = '';// string : the text of the rules
1148 public $mRulesAction = 'none';
1149 public $mFlags = array();
1150 public $mVariantFlags = array();
1151 public $mConvTable = array();
1152 public $mBidtable = array();// array of the translation in each variant
1153 public $mUnidtable = array();// array of the translation in each variant
1156 * Constructor
1158 * @param $text String: the text between -{ and }-
1159 * @param $converter LanguageConverter object
1161 public function __construct( $text, $converter ) {
1162 $this->mText = $text;
1163 $this->mConverter = $converter;
1167 * Check if variants array in convert array.
1169 * @param $variants Array or string: variant language code
1170 * @return String: translated text
1172 public function getTextInBidtable( $variants ) {
1173 $variants = (array)$variants;
1174 if ( !$variants ) {
1175 return false;
1177 foreach ( $variants as $variant ) {
1178 if ( isset( $this->mBidtable[$variant] ) ) {
1179 return $this->mBidtable[$variant];
1182 return false;
1186 * Parse flags with syntax -{FLAG| ... }-
1187 * @private
1189 function parseFlags() {
1190 $text = $this->mText;
1191 $flags = array();
1192 $variantFlags = array();
1194 $sepPos = strpos( $text, '|' );
1195 if ( $sepPos !== false ) {
1196 $validFlags = $this->mConverter->mFlags;
1197 $f = StringUtils::explode( ';', substr( $text, 0, $sepPos ) );
1198 foreach ( $f as $ff ) {
1199 $ff = trim( $ff );
1200 if ( isset( $validFlags[$ff] ) ) {
1201 $flags[$validFlags[$ff]] = true;
1204 $text = strval( substr( $text, $sepPos + 1 ) );
1207 if ( !$flags ) {
1208 $flags['S'] = true;
1209 } elseif ( isset( $flags['R'] ) ) {
1210 $flags = array( 'R' => true );// remove other flags
1211 } elseif ( isset( $flags['N'] ) ) {
1212 $flags = array( 'N' => true );// remove other flags
1213 } elseif ( isset( $flags['-'] ) ) {
1214 $flags = array( '-' => true );// remove other flags
1215 } elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
1216 $flags['H'] = true;
1217 } elseif ( isset( $flags['H'] ) ) {
1218 // replace A flag, and remove other flags except T
1219 $temp = array( '+' => true, 'H' => true );
1220 if ( isset( $flags['T'] ) ) {
1221 $temp['T'] = true;
1223 if ( isset( $flags['D'] ) ) {
1224 $temp['D'] = true;
1226 $flags = $temp;
1227 } else {
1228 if ( isset( $flags['A'] ) ) {
1229 $flags['+'] = true;
1230 $flags['S'] = true;
1232 if ( isset( $flags['D'] ) ) {
1233 unset( $flags['S'] );
1235 // try to find flags like "zh-hans", "zh-hant"
1236 // allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
1237 $variantFlags = array_intersect( array_keys( $flags ), $this->mConverter->mVariants );
1238 if ( $variantFlags ) {
1239 $variantFlags = array_flip( $variantFlags );
1240 $flags = array();
1243 $this->mVariantFlags = $variantFlags;
1244 $this->mRules = $text;
1245 $this->mFlags = $flags;
1249 * Generate conversion table.
1250 * @private
1252 function parseRules() {
1253 $rules = $this->mRules;
1254 $bidtable = array();
1255 $unidtable = array();
1256 $variants = $this->mConverter->mVariants;
1257 $varsep_pattern = $this->mConverter->getVarSeparatorPattern();
1259 $choice = preg_split( $varsep_pattern, $rules );
1261 foreach ( $choice as $c ) {
1262 $v = explode( ':', $c, 2 );
1263 if ( count( $v ) != 2 ) {
1264 // syntax error, skip
1265 continue;
1267 $to = trim( $v[1] );
1268 $v = trim( $v[0] );
1269 $u = explode( '=>', $v, 2 );
1270 // if $to is empty, strtr() could return a wrong result
1271 if ( count( $u ) == 1 && $to && in_array( $v, $variants ) ) {
1272 $bidtable[$v] = $to;
1273 } elseif ( count( $u ) == 2 ) {
1274 $from = trim( $u[0] );
1275 $v = trim( $u[1] );
1276 if ( array_key_exists( $v, $unidtable )
1277 && !is_array( $unidtable[$v] )
1278 && $to
1279 && in_array( $v, $variants ) ) {
1280 $unidtable[$v] = array( $from => $to );
1281 } elseif ( $to && in_array( $v, $variants ) ) {
1282 $unidtable[$v][$from] = $to;
1285 // syntax error, pass
1286 if ( !isset( $this->mConverter->mVariantNames[$v] ) ) {
1287 $bidtable = array();
1288 $unidtable = array();
1289 break;
1292 $this->mBidtable = $bidtable;
1293 $this->mUnidtable = $unidtable;
1297 * @private
1299 * @return string
1301 function getRulesDesc() {
1302 $codesep = $this->mConverter->mDescCodeSep;
1303 $varsep = $this->mConverter->mDescVarSep;
1304 $text = '';
1305 foreach ( $this->mBidtable as $k => $v ) {
1306 $text .= $this->mConverter->mVariantNames[$k] . "$codesep$v$varsep";
1308 foreach ( $this->mUnidtable as $k => $a ) {
1309 foreach ( $a as $from => $to ) {
1310 $text .= $from . '⇒' . $this->mConverter->mVariantNames[$k] .
1311 "$codesep$to$varsep";
1314 return $text;
1318 * Parse rules conversion.
1319 * @private
1321 * @param $variant
1323 * @return string
1325 function getRuleConvertedStr( $variant ) {
1326 $bidtable = $this->mBidtable;
1327 $unidtable = $this->mUnidtable;
1329 if ( count( $bidtable ) + count( $unidtable ) == 0 ) {
1330 return $this->mRules;
1331 } else {
1332 // display current variant in bidirectional array
1333 $disp = $this->getTextInBidtable( $variant );
1334 // or display current variant in fallbacks
1335 if ( !$disp ) {
1336 $disp = $this->getTextInBidtable(
1337 $this->mConverter->getVariantFallbacks( $variant ) );
1339 // or display current variant in unidirectional array
1340 if ( !$disp && array_key_exists( $variant, $unidtable ) ) {
1341 $disp = array_values( $unidtable[$variant] );
1342 $disp = $disp[0];
1344 // or display frist text under disable manual convert
1345 if ( !$disp
1346 && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
1347 if ( count( $bidtable ) > 0 ) {
1348 $disp = array_values( $bidtable );
1349 $disp = $disp[0];
1350 } else {
1351 $disp = array_values( $unidtable );
1352 $disp = array_values( $disp[0] );
1353 $disp = $disp[0];
1356 return $disp;
1361 * Generate conversion table for all text.
1362 * @private
1364 function generateConvTable() {
1365 // Special case optimisation
1366 if ( !$this->mBidtable && !$this->mUnidtable ) {
1367 $this->mConvTable = array();
1368 return;
1371 $bidtable = $this->mBidtable;
1372 $unidtable = $this->mUnidtable;
1373 $manLevel = $this->mConverter->mManualLevel;
1375 $vmarked = array();
1376 foreach ( $this->mConverter->mVariants as $v ) {
1377 /* for bidirectional array
1378 fill in the missing variants, if any,
1379 with fallbacks */
1380 if ( !isset( $bidtable[$v] ) ) {
1381 $variantFallbacks =
1382 $this->mConverter->getVariantFallbacks( $v );
1383 $vf = $this->getTextInBidtable( $variantFallbacks );
1384 if ( $vf ) {
1385 $bidtable[$v] = $vf;
1389 if ( isset( $bidtable[$v] ) ) {
1390 foreach ( $vmarked as $vo ) {
1391 // use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
1392 // or -{H|zh:WordZh;zh-tw:WordTw}-
1393 // or -{-|zh:WordZh;zh-tw:WordTw}-
1394 // to introduce a custom mapping between
1395 // words WordZh and WordTw in the whole text
1396 if ( $manLevel[$v] == 'bidirectional' ) {
1397 $this->mConvTable[$v][$bidtable[$vo]] = $bidtable[$v];
1399 if ( $manLevel[$vo] == 'bidirectional' ) {
1400 $this->mConvTable[$vo][$bidtable[$v]] = $bidtable[$vo];
1403 $vmarked[] = $v;
1405 /* for unidirectional array fill to convert tables */
1406 if ( ( $manLevel[$v] == 'bidirectional' || $manLevel[$v] == 'unidirectional' )
1407 && isset( $unidtable[$v] ) )
1409 if ( isset( $this->mConvTable[$v] ) ) {
1410 $this->mConvTable[$v] = array_merge( $this->mConvTable[$v], $unidtable[$v] );
1411 } else {
1412 $this->mConvTable[$v] = $unidtable[$v];
1419 * Parse rules and flags.
1420 * @param $variant String: variant language code
1422 public function parse( $variant = null ) {
1423 if ( !$variant ) {
1424 $variant = $this->mConverter->getPreferredVariant();
1427 $this->parseFlags();
1428 $flags = $this->mFlags;
1430 // convert to specified variant
1431 // syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
1432 if ( $this->mVariantFlags ) {
1433 // check if current variant in flags
1434 if ( isset( $this->mVariantFlags[$variant] ) ) {
1435 // then convert <text to convert> to current language
1436 $this->mRules = $this->mConverter->autoConvert( $this->mRules,
1437 $variant );
1438 } else { // if current variant no in flags,
1439 // then we check its fallback variants.
1440 $variantFallbacks =
1441 $this->mConverter->getVariantFallbacks( $variant );
1442 if ( is_array( $variantFallbacks ) ) {
1443 foreach ( $variantFallbacks as $variantFallback ) {
1444 // if current variant's fallback exist in flags
1445 if ( isset( $this->mVariantFlags[$variantFallback] ) ) {
1446 // then convert <text to convert> to fallback language
1447 $this->mRules =
1448 $this->mConverter->autoConvert( $this->mRules,
1449 $variantFallback );
1450 break;
1455 $this->mFlags = $flags = array( 'R' => true );
1458 if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
1459 // decode => HTML entities modified by Sanitizer::removeHTMLtags
1460 $this->mRules = str_replace( '=&gt;', '=>', $this->mRules );
1461 $this->parseRules();
1463 $rules = $this->mRules;
1465 if ( !$this->mBidtable && !$this->mUnidtable ) {
1466 if ( isset( $flags['+'] ) || isset( $flags['-'] ) ) {
1467 // fill all variants if text in -{A/H/-|text} without rules
1468 foreach ( $this->mConverter->mVariants as $v ) {
1469 $this->mBidtable[$v] = $rules;
1471 } elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
1472 $this->mFlags = $flags = array( 'R' => true );
1476 $this->mRuleDisplay = false;
1477 foreach ( $flags as $flag => $unused ) {
1478 switch ( $flag ) {
1479 case 'R':
1480 // if we don't do content convert, still strip the -{}- tags
1481 $this->mRuleDisplay = $rules;
1482 break;
1483 case 'N':
1484 // process N flag: output current variant name
1485 $ruleVar = trim( $rules );
1486 if ( isset( $this->mConverter->mVariantNames[$ruleVar] ) ) {
1487 $this->mRuleDisplay = $this->mConverter->mVariantNames[$ruleVar];
1488 } else {
1489 $this->mRuleDisplay = '';
1491 break;
1492 case 'D':
1493 // process D flag: output rules description
1494 $this->mRuleDisplay = $this->getRulesDesc();
1495 break;
1496 case 'H':
1497 // process H,- flag or T only: output nothing
1498 $this->mRuleDisplay = '';
1499 break;
1500 case '-':
1501 $this->mRulesAction = 'remove';
1502 $this->mRuleDisplay = '';
1503 break;
1504 case '+':
1505 $this->mRulesAction = 'add';
1506 $this->mRuleDisplay = '';
1507 break;
1508 case 'S':
1509 $this->mRuleDisplay = $this->getRuleConvertedStr( $variant );
1510 break;
1511 case 'T':
1512 $this->mRuleTitle = $this->getRuleConvertedStr( $variant );
1513 $this->mRuleDisplay = '';
1514 break;
1515 default:
1516 // ignore unknown flags (but see error case below)
1519 if ( $this->mRuleDisplay === false ) {
1520 $this->mRuleDisplay = '<span class="error">'
1521 . wfMessage( 'converter-manual-rule-error' )->inContentLanguage()->escaped()
1522 . '</span>';
1525 $this->generateConvTable();
1529 * @todo FIXME: code this function :)
1531 public function hasRules() {
1532 // TODO:
1536 * Get display text on markup -{...}-
1537 * @return string
1539 public function getDisplay() {
1540 return $this->mRuleDisplay;
1544 * Get converted title.
1545 * @return string
1547 public function getTitle() {
1548 return $this->mRuleTitle;
1552 * Return how deal with conversion rules.
1553 * @return string
1555 public function getRulesAction() {
1556 return $this->mRulesAction;
1560 * Get conversion table. (bidirectional and unidirectional
1561 * conversion table)
1562 * @return array
1564 public function getConvTable() {
1565 return $this->mConvTable;
1569 * Get conversion rules string.
1570 * @return string
1572 public function getRules() {
1573 return $this->mRules;
1577 * Get conversion flags.
1578 * @return array
1580 public function getFlags() {
1581 return $this->mFlags;