00bc02db4582e597a5f37f91ee6c9f11a422587b
[lhc/web/wiklou.git] / languages / LanguageConverter.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Language
20 */
21 use MediaWiki\MediaWikiServices;
22
23 use MediaWiki\Logger\LoggerFactory;
24
25 /**
26 * Base class for language conversion.
27 * @ingroup Language
28 *
29 * @author Zhengzhu Feng <zhengzhu@gmail.com>
30 * @author fdcn <fdcn64@gmail.com>
31 * @author shinjiman <shinjiman@gmail.com>
32 * @author PhiLiP <philip.npc@gmail.com>
33 */
34 class LanguageConverter {
35 /**
36 * languages supporting variants
37 * @since 1.20
38 * @var array
39 */
40 static public $languagesWithVariants = [
41 'en',
42 'gan',
43 'iu',
44 'kk',
45 'ku',
46 'shi',
47 'sr',
48 'tg',
49 'uz',
50 'zh',
51 ];
52
53 public $mMainLanguageCode;
54
55 /**
56 * @var string[]
57 */
58 public $mVariants;
59 public $mVariantFallbacks;
60 public $mVariantNames;
61 public $mTablesLoaded = false;
62 public $mTables;
63 // 'bidirectional' 'unidirectional' 'disable' for each variant
64 public $mManualLevel;
65
66 public $mLangObj;
67 public $mFlags;
68 public $mDescCodeSep = ':', $mDescVarSep = ';';
69 public $mUcfirst = false;
70 public $mConvRuleTitle = false;
71 public $mURLVariant;
72 public $mUserVariant;
73 public $mHeaderVariant;
74 public $mMaxDepth = 10;
75 public $mVarSeparatorPattern;
76
77 const CACHE_VERSION_KEY = 'VERSION 7';
78
79 /**
80 * @param Language $langobj
81 * @param string $maincode The main language code of this language
82 * @param string[] $variants The supported variants of this language
83 * @param array $variantfallbacks The fallback language of each variant
84 * @param array $flags Defining the custom strings that maps to the flags
85 * @param array $manualLevel Limit for supported variants
86 */
87 public function __construct( $langobj, $maincode, $variants = [],
88 $variantfallbacks = [], $flags = [],
89 $manualLevel = [] ) {
90 global $wgDisabledVariants;
91 $this->mLangObj = $langobj;
92 $this->mMainLanguageCode = $maincode;
93 $this->mVariants = array_diff( $variants, $wgDisabledVariants );
94 $this->mVariantFallbacks = $variantfallbacks;
95 $this->mVariantNames = Language::fetchLanguageNames();
96 $defaultflags = [
97 // 'S' show converted text
98 // '+' add rules for alltext
99 // 'E' the gave flags is error
100 // these flags above are reserved for program
101 'A' => 'A', // add rule for convert code (all text convert)
102 'T' => 'T', // title convert
103 'R' => 'R', // raw content
104 'D' => 'D', // convert description (subclass implement)
105 '-' => '-', // remove convert (not implement)
106 'H' => 'H', // add rule for convert code (but no display in placed code)
107 'N' => 'N', // current variant name
108 ];
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';
115 }
116 $this->mFlags[$v] = $v;
117 }
118 }
119
120 /**
121 * Get all valid variants.
122 * Call this instead of using $this->mVariants directly.
123 *
124 * @return string[] Contains all valid variants
125 */
126 public function getVariants() {
127 return $this->mVariants;
128 }
129
130 /**
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.
136 *
137 * @param string $variant 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
140 */
141 public function getVariantFallbacks( $variant ) {
142 if ( isset( $this->mVariantFallbacks[$variant] ) ) {
143 return $this->mVariantFallbacks[$variant];
144 }
145 return $this->mMainLanguageCode;
146 }
147
148 /**
149 * Get the title produced by the conversion rule.
150 * @return string The converted title text
151 */
152 public function getConvRuleTitle() {
153 return $this->mConvRuleTitle;
154 }
155
156 /**
157 * Get preferred language variant.
158 * @return string The preferred language code
159 */
160 public function getPreferredVariant() {
161 global $wgDefaultLanguageVariant, $wgUser;
162
163 $req = $this->getURLVariant();
164
165 if ( $wgUser->isSafeToLoad() && $wgUser->isLoggedIn() && !$req ) {
166 $req = $this->getUserVariant();
167 } elseif ( !$req ) {
168 $req = $this->getHeaderVariant();
169 }
170
171 if ( $wgDefaultLanguageVariant && !$req ) {
172 $req = $this->validateVariant( $wgDefaultLanguageVariant );
173 }
174
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;
181 }
182 return $this->mMainLanguageCode;
183 }
184
185 /**
186 * Get default variant.
187 * This function would not be affected by user's settings
188 * @return string The default variant code
189 */
190 public function getDefaultVariant() {
191 global $wgDefaultLanguageVariant;
192
193 $req = $this->getURLVariant();
194
195 if ( !$req ) {
196 $req = $this->getHeaderVariant();
197 }
198
199 if ( $wgDefaultLanguageVariant && !$req ) {
200 $req = $this->validateVariant( $wgDefaultLanguageVariant );
201 }
202
203 if ( $req ) {
204 return $req;
205 }
206 return $this->mMainLanguageCode;
207 }
208
209 /**
210 * Validate the variant
211 * @param string $variant The variant to validate
212 * @return mixed Returns the variant if it is valid, null otherwise
213 */
214 public function validateVariant( $variant = null ) {
215 if ( $variant !== null && in_array( $variant, $this->mVariants ) ) {
216 return $variant;
217 }
218 return null;
219 }
220
221 /**
222 * Get the variant specified in the URL
223 *
224 * @return mixed Variant if one found, false otherwise.
225 */
226 public function getURLVariant() {
227 global $wgRequest;
228
229 if ( $this->mURLVariant ) {
230 return $this->mURLVariant;
231 }
232
233 // see if the preference is set in the request
234 $ret = $wgRequest->getText( 'variant' );
235
236 if ( !$ret ) {
237 $ret = $wgRequest->getVal( 'uselang' );
238 }
239
240 $this->mURLVariant = $this->validateVariant( $ret );
241 return $this->mURLVariant;
242 }
243
244 /**
245 * Determine if the user has a variant set.
246 *
247 * @return mixed Variant if one found, false otherwise.
248 */
249 protected function getUserVariant() {
250 global $wgUser, $wgContLang;
251
252 // memoizing this function wreaks havoc on parserTest.php
253 /*
254 if ( $this->mUserVariant ) {
255 return $this->mUserVariant;
256 }
257 */
258
259 // Get language variant preference from logged in users
260 // Don't call this on stub objects because that causes infinite
261 // recursion during initialisation
262 if ( !$wgUser->isSafeToLoad() ) {
263 return false;
264 }
265 if ( $wgUser->isLoggedIn() ) {
266 if ( $this->mMainLanguageCode == $wgContLang->getCode() ) {
267 $ret = $wgUser->getOption( 'variant' );
268 } else {
269 $ret = $wgUser->getOption( 'variant-' . $this->mMainLanguageCode );
270 }
271 } else {
272 // figure out user lang without constructing wgLang to avoid
273 // infinite recursion
274 $ret = $wgUser->getOption( 'language' );
275 }
276
277 $this->mUserVariant = $this->validateVariant( $ret );
278 return $this->mUserVariant;
279 }
280
281 /**
282 * Determine the language variant from the Accept-Language header.
283 *
284 * @return mixed Variant if one found, false otherwise.
285 */
286 protected function getHeaderVariant() {
287 global $wgRequest;
288
289 if ( $this->mHeaderVariant ) {
290 return $this->mHeaderVariant;
291 }
292
293 // see if some supported language variant is set in the
294 // HTTP header.
295 $languages = array_keys( $wgRequest->getAcceptLang() );
296 if ( empty( $languages ) ) {
297 return null;
298 }
299
300 $fallbackLanguages = [];
301 foreach ( $languages as $language ) {
302 $this->mHeaderVariant = $this->validateVariant( $language );
303 if ( $this->mHeaderVariant ) {
304 break;
305 }
306
307 // To see if there are fallbacks of current language.
308 // We record these fallback variants, and process
309 // them later.
310 $fallbacks = $this->getVariantFallbacks( $language );
311 if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode ) {
312 $fallbackLanguages[] = $fallbacks;
313 } elseif ( is_array( $fallbacks ) ) {
314 $fallbackLanguages =
315 array_merge( $fallbackLanguages, $fallbacks );
316 }
317 }
318
319 if ( !$this->mHeaderVariant ) {
320 // process fallback languages now
321 $fallback_languages = array_unique( $fallbackLanguages );
322 foreach ( $fallback_languages as $language ) {
323 $this->mHeaderVariant = $this->validateVariant( $language );
324 if ( $this->mHeaderVariant ) {
325 break;
326 }
327 }
328 }
329
330 return $this->mHeaderVariant;
331 }
332
333 /**
334 * Dictionary-based conversion.
335 * This function would not parse the conversion rules.
336 * If you want to parse rules, try to use convert() or
337 * convertTo().
338 *
339 * @param string $text The text to be converted
340 * @param bool|string $toVariant The target language code
341 * @return string The converted text
342 */
343 public function autoConvert( $text, $toVariant = false ) {
344 $this->loadTables();
345
346 if ( !$toVariant ) {
347 $toVariant = $this->getPreferredVariant();
348 if ( !$toVariant ) {
349 return $text;
350 }
351 }
352
353 if ( $this->guessVariant( $text, $toVariant ) ) {
354 return $text;
355 }
356
357 /* we convert everything except:
358 1. HTML markups (anything between < and >)
359 2. HTML entities
360 3. placeholders created by the parser
361 IMPORTANT: Beware of failure from pcre.backtrack_limit (T124404).
362 Minimize use of backtracking where possible.
363 */
364 $marker = '|' . Parser::MARKER_PREFIX . '[^\x7f]++\x7f';
365
366 // this one is needed when the text is inside an HTML markup
367 $htmlfix = '|<[^>\004]++(?=\004$)|^[^<>]*+>';
368
369 // Optimize for the common case where these tags have
370 // few or no children. Thus try and possesively get as much as
371 // possible, and only engage in backtracking when we hit a '<'.
372
373 // disable convert to variants between <code> tags
374 $codefix = '<code>[^<]*+(?:(?:(?!<\/code>).)[^<]*+)*+<\/code>|';
375 // disable conversion of <script> tags
376 $scriptfix = '<script[^>]*+>[^<]*+(?:(?:(?!<\/script>).)[^<]*+)*+<\/script>|';
377 // disable conversion of <pre> tags
378 $prefix = '<pre[^>]*+>[^<]*+(?:(?:(?!<\/pre>).)[^<]*+)*+<\/pre>|';
379
380 $reg = '/' . $codefix . $scriptfix . $prefix .
381 '<[^>]++>|&[a-zA-Z#][a-z0-9]++;' . $marker . $htmlfix . '|\004$/s';
382 $startPos = 0;
383 $sourceBlob = '';
384 $literalBlob = '';
385
386 // Guard against delimiter nulls in the input
387 // (should never happen: see T159174)
388 $text = str_replace( "\000", '', $text );
389
390 $markupMatches = null;
391 $elementMatches = null;
392
393 // We add a marker (\004) at the end of text, to ensure we always match the
394 // entire text (Otherwise, pcre.backtrack_limit might cause silent failure)
395 while ( $startPos < strlen( $text ) ) {
396 if ( preg_match( $reg, $text . "\004", $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
397 $elementPos = $markupMatches[0][1];
398 $element = $markupMatches[0][0];
399 if ( $element === "\004" ) {
400 // We hit the end.
401 $elementPos = strlen( $text );
402 $element = '';
403 }
404 } else {
405 // If we hit here, then Language Converter could be tricked
406 // into doing an XSS, so we refuse to translate.
407 // If non-crazy input manages to reach this code path,
408 // we should consider it a bug.
409 $log = LoggerFactory::getInstance( 'languageconverter' );
410 $log->error( "Hit pcre.backtrack_limit in " . __METHOD__
411 . ". Disabling language conversion for this page.",
412 array(
413 "method" => __METHOD__,
414 "variant" => $toVariant,
415 "startOfText" => substr( $text, 0, 500 )
416 )
417 );
418 return $text;
419 }
420 // Queue the part before the markup for translation in a batch
421 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
422
423 // Advance to the next position
424 $startPos = $elementPos + strlen( $element );
425
426 // Translate any alt or title attributes inside the matched element
427 if ( $element !== ''
428 && preg_match( '/^(<[^>\s]*+)\s([^>]*+)(.*+)$/', $element, $elementMatches )
429 ) {
430 $attrs = Sanitizer::decodeTagAttributes( $elementMatches[2] );
431 $changed = false;
432 foreach ( [ 'title', 'alt' ] as $attrName ) {
433 if ( !isset( $attrs[$attrName] ) ) {
434 continue;
435 }
436 $attr = $attrs[$attrName];
437 // Don't convert URLs
438 if ( !strpos( $attr, '://' ) ) {
439 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
440 }
441
442 if ( $attr !== $attrs[$attrName] ) {
443 $attrs[$attrName] = $attr;
444 $changed = true;
445 }
446 }
447 if ( $changed ) {
448 $element = $elementMatches[1] . Html::expandAttributes( $attrs ) .
449 $elementMatches[3];
450 }
451 }
452 $literalBlob .= $element . "\000";
453 }
454
455 // Do the main translation batch
456 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
457
458 // Put the output back together
459 $translatedIter = StringUtils::explode( "\000", $translatedBlob );
460 $literalIter = StringUtils::explode( "\000", $literalBlob );
461 $output = '';
462 while ( $translatedIter->valid() && $literalIter->valid() ) {
463 $output .= $translatedIter->current();
464 $output .= $literalIter->current();
465 $translatedIter->next();
466 $literalIter->next();
467 }
468
469 return $output;
470 }
471
472 /**
473 * Translate a string to a variant.
474 * Doesn't parse rules or do any of that other stuff, for that use
475 * convert() or convertTo().
476 *
477 * @param string $text Text to convert
478 * @param string $variant Variant language code
479 * @return string Translated text
480 */
481 public function translate( $text, $variant ) {
482 // If $text is empty or only includes spaces, do nothing
483 // Otherwise translate it
484 if ( trim( $text ) ) {
485 $this->loadTables();
486 $text = $this->mTables[$variant]->replace( $text );
487 }
488 return $text;
489 }
490
491 /**
492 * Call translate() to convert text to all valid variants.
493 *
494 * @param string $text The text to be converted
495 * @return array Variant => converted text
496 */
497 public function autoConvertToAllVariants( $text ) {
498 $this->loadTables();
499
500 $ret = [];
501 foreach ( $this->mVariants as $variant ) {
502 $ret[$variant] = $this->translate( $text, $variant );
503 }
504
505 return $ret;
506 }
507
508 /**
509 * Apply manual conversion rules.
510 *
511 * @param ConverterRule $convRule
512 */
513 protected function applyManualConv( $convRule ) {
514 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
515 // title conversion.
516 // T26072: $mConvRuleTitle was overwritten by other manual
517 // rule(s) not for title, this breaks the title conversion.
518 $newConvRuleTitle = $convRule->getTitle();
519 if ( $newConvRuleTitle ) {
520 // So I add an empty check for getTitle()
521 $this->mConvRuleTitle = $newConvRuleTitle;
522 }
523
524 // merge/remove manual conversion rules to/from global table
525 $convTable = $convRule->getConvTable();
526 $action = $convRule->getRulesAction();
527 foreach ( $convTable as $variant => $pair ) {
528 if ( !$this->validateVariant( $variant ) ) {
529 continue;
530 }
531
532 if ( $action == 'add' ) {
533 // More efficient than array_merge(), about 2.5 times.
534 foreach ( $pair as $from => $to ) {
535 $this->mTables[$variant]->setPair( $from, $to );
536 }
537 } elseif ( $action == 'remove' ) {
538 $this->mTables[$variant]->removeArray( $pair );
539 }
540 }
541 }
542
543 /**
544 * Auto convert a Title object to a readable string in the
545 * preferred variant.
546 *
547 * @param Title $title A object of Title
548 * @return string Converted title text
549 */
550 public function convertTitle( $title ) {
551 $variant = $this->getPreferredVariant();
552 $index = $title->getNamespace();
553 if ( $index !== NS_MAIN ) {
554 $text = $this->convertNamespace( $index, $variant ) . ':';
555 } else {
556 $text = '';
557 }
558 $text .= $this->translate( $title->getText(), $variant );
559 return $text;
560 }
561
562 /**
563 * Get the namespace display name in the preferred variant.
564 *
565 * @param int $index Namespace id
566 * @param string|null $variant Variant code or null for preferred variant
567 * @return string Namespace name for display
568 */
569 public function convertNamespace( $index, $variant = null ) {
570 if ( $index === NS_MAIN ) {
571 return '';
572 }
573
574 if ( $variant === null ) {
575 $variant = $this->getPreferredVariant();
576 }
577
578 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
579 $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
580 $nsVariantText = $cache->get( $key );
581 if ( $nsVariantText !== false ) {
582 return $nsVariantText;
583 }
584
585 // First check if a message gives a converted name in the target variant.
586 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
587 if ( $nsConvMsg->exists() ) {
588 $nsVariantText = $nsConvMsg->plain();
589 }
590
591 // Then check if a message gives a converted name in content language
592 // which needs extra translation to the target variant.
593 if ( $nsVariantText === false ) {
594 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
595 if ( $nsConvMsg->exists() ) {
596 $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
597 }
598 }
599
600 if ( $nsVariantText === false ) {
601 // No message exists, retrieve it from the target variant's namespace names.
602 $langObj = $this->mLangObj->factory( $variant );
603 $nsVariantText = $langObj->getFormattedNsText( $index );
604 }
605
606 $cache->set( $key, $nsVariantText, 60 );
607
608 return $nsVariantText;
609 }
610
611 /**
612 * Convert text to different variants of a language. The automatic
613 * conversion is done in autoConvert(). Here we parse the text
614 * marked with -{}-, which specifies special conversions of the
615 * text that can not be accomplished in autoConvert().
616 *
617 * Syntax of the markup:
618 * -{code1:text1;code2:text2;...}- or
619 * -{flags|code1:text1;code2:text2;...}- or
620 * -{text}- in which case no conversion should take place for text
621 *
622 * @param string $text Text to be converted
623 * @return string Converted text
624 */
625 public function convert( $text ) {
626 $variant = $this->getPreferredVariant();
627 return $this->convertTo( $text, $variant );
628 }
629
630 /**
631 * Same as convert() except a extra parameter to custom variant.
632 *
633 * @param string $text Text to be converted
634 * @param string $variant The target variant code
635 * @return string Converted text
636 */
637 public function convertTo( $text, $variant ) {
638 global $wgDisableLangConversion;
639 if ( $wgDisableLangConversion ) {
640 return $text;
641 }
642 // Reset converter state for a new converter run.
643 $this->mConvRuleTitle = false;
644 return $this->recursiveConvertTopLevel( $text, $variant );
645 }
646
647 /**
648 * Recursively convert text on the outside. Allow to use nested
649 * markups to custom rules.
650 *
651 * @param string $text Text to be converted
652 * @param string $variant The target variant code
653 * @param int $depth Depth of recursion
654 * @return string Converted text
655 */
656 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
657 $startPos = 0;
658 $out = '';
659 $length = strlen( $text );
660 $shouldConvert = !$this->guessVariant( $text, $variant );
661
662 while ( $startPos < $length ) {
663 $pos = strpos( $text, '-{', $startPos );
664
665 if ( $pos === false ) {
666 // No more markup, append final segment
667 $fragment = substr( $text, $startPos );
668 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
669 return $out;
670 }
671
672 // Markup found
673 // Append initial segment
674 $fragment = substr( $text, $startPos, $pos - $startPos );
675 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
676
677 // Advance position
678 $startPos = $pos;
679
680 // Do recursive conversion
681 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
682 }
683
684 return $out;
685 }
686
687 /**
688 * Recursively convert text on the inside.
689 *
690 * @param string $text Text to be converted
691 * @param string $variant The target variant code
692 * @param int &$startPos
693 * @param int $depth Depth of recursion
694 *
695 * @throws MWException
696 * @return string Converted text
697 */
698 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
699 // Quick sanity check (no function calls)
700 if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
701 throw new MWException( __METHOD__ . ': invalid input string' );
702 }
703
704 $startPos += 2;
705 $inner = '';
706 $warningDone = false;
707 $length = strlen( $text );
708
709 while ( $startPos < $length ) {
710 $m = false;
711 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
712 if ( !$m ) {
713 // Unclosed rule
714 break;
715 }
716
717 $token = $m[0][0];
718 $pos = $m[0][1];
719
720 // Markup found
721 // Append initial segment
722 $inner .= substr( $text, $startPos, $pos - $startPos );
723
724 // Advance position
725 $startPos = $pos;
726
727 switch ( $token ) {
728 case '-{':
729 // Check max depth
730 if ( $depth >= $this->mMaxDepth ) {
731 $inner .= '-{';
732 if ( !$warningDone ) {
733 $inner .= '<span class="error">' .
734 wfMessage( 'language-converter-depth-warning' )
735 ->numParams( $this->mMaxDepth )->inContentLanguage()->text() .
736 '</span>';
737 $warningDone = true;
738 }
739 $startPos += 2;
740 continue;
741 }
742 // Recursively parse another rule
743 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
744 break;
745 case '}-':
746 // Apply the rule
747 $startPos += 2;
748 $rule = new ConverterRule( $inner, $this );
749 $rule->parse( $variant );
750 $this->applyManualConv( $rule );
751 return $rule->getDisplay();
752 default:
753 throw new MWException( __METHOD__ . ': invalid regex match' );
754 }
755 }
756
757 // Unclosed rule
758 if ( $startPos < $length ) {
759 $inner .= substr( $text, $startPos );
760 }
761 $startPos = $length;
762 return '-{' . $this->autoConvert( $inner, $variant );
763 }
764
765 /**
766 * If a language supports multiple variants, it is possible that
767 * non-existing link in one variant actually exists in another variant.
768 * This function tries to find it. See e.g. LanguageZh.php
769 * The input parameters may be modified upon return
770 *
771 * @param string &$link The name of the link
772 * @param Title &$nt The title object of the link
773 * @param bool $ignoreOtherCond To disable other conditions when
774 * we need to transclude a template or update a category's link
775 */
776 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
777 # If the article has already existed, there is no need to
778 # check it again, otherwise it may cause a fault.
779 if ( is_object( $nt ) && $nt->exists() ) {
780 return;
781 }
782
783 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
784 $isredir = $wgRequest->getText( 'redirect', 'yes' );
785 $action = $wgRequest->getText( 'action' );
786 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
787 $action = 'view';
788 }
789 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
790 $disableLinkConversion = $wgDisableLangConversion
791 || $wgDisableTitleConversion;
792 $linkBatch = new LinkBatch();
793
794 $ns = NS_MAIN;
795
796 if ( $disableLinkConversion ||
797 ( !$ignoreOtherCond &&
798 ( $isredir == 'no'
799 || $action == 'edit'
800 || $action == 'submit'
801 || $linkconvert == 'no' ) ) ) {
802 return;
803 }
804
805 if ( is_object( $nt ) ) {
806 $ns = $nt->getNamespace();
807 }
808
809 $variants = $this->autoConvertToAllVariants( $link );
810 if ( !$variants ) { // give up
811 return;
812 }
813
814 $titles = [];
815
816 foreach ( $variants as $v ) {
817 if ( $v != $link ) {
818 $varnt = Title::newFromText( $v, $ns );
819 if ( !is_null( $varnt ) ) {
820 $linkBatch->addObj( $varnt );
821 $titles[] = $varnt;
822 }
823 }
824 }
825
826 // fetch all variants in single query
827 $linkBatch->execute();
828
829 foreach ( $titles as $varnt ) {
830 if ( $varnt->getArticleID() > 0 ) {
831 $nt = $varnt;
832 $link = $varnt->getText();
833 break;
834 }
835 }
836 }
837
838 /**
839 * Returns language specific hash options.
840 *
841 * @return string
842 */
843 public function getExtraHashOptions() {
844 $variant = $this->getPreferredVariant();
845
846 return '!' . $variant;
847 }
848
849 /**
850 * Guess if a text is written in a variant. This should be implemented in subclasses.
851 *
852 * @param string $text The text to be checked
853 * @param string $variant Language code of the variant to be checked for
854 * @return bool True if $text appears to be written in $variant, false if not
855 *
856 * @author Nikola Smolenski <smolensk@eunet.rs>
857 * @since 1.19
858 */
859 public function guessVariant( $text, $variant ) {
860 return false;
861 }
862
863 /**
864 * Load default conversion tables.
865 * This method must be implemented in derived class.
866 *
867 * @private
868 * @throws MWException
869 */
870 function loadDefaultTables() {
871 $class = static::class;
872 throw new MWException( "Must implement loadDefaultTables() method in class $class" );
873 }
874
875 /**
876 * Load conversion tables either from the cache or the disk.
877 * @private
878 * @param bool $fromCache Load from memcached? Defaults to true.
879 */
880 function loadTables( $fromCache = true ) {
881 global $wgLanguageConverterCacheType;
882
883 if ( $this->mTablesLoaded ) {
884 return;
885 }
886
887 $this->mTablesLoaded = true;
888 $this->mTables = false;
889 $cache = ObjectCache::getInstance( $wgLanguageConverterCacheType );
890 $cacheKey = $cache->makeKey( 'conversiontables', $this->mMainLanguageCode );
891 if ( $fromCache ) {
892 $this->mTables = $cache->get( $cacheKey );
893 }
894 if ( !$this->mTables || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
895 // not in cache, or we need a fresh reload.
896 // We will first load the default tables
897 // then update them using things in MediaWiki:Conversiontable/*
898 $this->loadDefaultTables();
899 foreach ( $this->mVariants as $var ) {
900 $cached = $this->parseCachedTable( $var );
901 $this->mTables[$var]->mergeArray( $cached );
902 }
903
904 $this->postLoadTables();
905 $this->mTables[self::CACHE_VERSION_KEY] = true;
906
907 $cache->set( $cacheKey, $this->mTables, 43200 );
908 }
909 }
910
911 /**
912 * Hook for post processing after conversion tables are loaded.
913 */
914 function postLoadTables() {
915 }
916
917 /**
918 * Reload the conversion tables.
919 *
920 * Also used by test suites which need to reset the converter state.
921 *
922 * @private
923 */
924 private function reloadTables() {
925 if ( $this->mTables ) {
926 unset( $this->mTables );
927 }
928
929 $this->mTablesLoaded = false;
930 $this->loadTables( false );
931 }
932
933 /**
934 * Parse the conversion table stored in the cache.
935 *
936 * The tables should be in blocks of the following form:
937 * -{
938 * word => word ;
939 * word => word ;
940 * ...
941 * }-
942 *
943 * To make the tables more manageable, subpages are allowed
944 * and will be parsed recursively if $recursive == true.
945 *
946 * @param string $code Language code
947 * @param string $subpage Subpage name
948 * @param bool $recursive Parse subpages recursively? Defaults to true.
949 *
950 * @return array
951 */
952 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
953 static $parsed = [];
954
955 $key = 'Conversiontable/' . $code;
956 if ( $subpage ) {
957 $key .= '/' . $subpage;
958 }
959 if ( array_key_exists( $key, $parsed ) ) {
960 return [];
961 }
962
963 $parsed[$key] = true;
964
965 if ( $subpage === '' ) {
966 $txt = MessageCache::singleton()->getMsgFromNamespace( $key, $code );
967 } else {
968 $txt = false;
969 $title = Title::makeTitleSafe( NS_MEDIAWIKI, $key );
970 if ( $title && $title->exists() ) {
971 $revision = Revision::newFromTitle( $title );
972 if ( $revision ) {
973 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT ) {
974 $txt = $revision->getContent( Revision::RAW )->getNativeData();
975 }
976
977 // @todo in the future, use a specialized content model, perhaps based on json!
978 }
979 }
980 }
981
982 # Nothing to parse if there's no text
983 if ( $txt === false || $txt === null || $txt === '' ) {
984 return [];
985 }
986
987 // get all subpage links of the form
988 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
989 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
990 ':Conversiontable';
991 $subs = StringUtils::explode( '[[', $txt );
992 $sublinks = [];
993 foreach ( $subs as $sub ) {
994 $link = explode( ']]', $sub, 2 );
995 if ( count( $link ) != 2 ) {
996 continue;
997 }
998 $b = explode( '|', $link[0], 2 );
999 $b = explode( '/', trim( $b[0] ), 3 );
1000 if ( count( $b ) == 3 ) {
1001 $sublink = $b[2];
1002 } else {
1003 $sublink = '';
1004 }
1005
1006 if ( $b[0] == $linkhead && $b[1] == $code ) {
1007 $sublinks[] = $sublink;
1008 }
1009 }
1010
1011 // parse the mappings in this page
1012 $blocks = StringUtils::explode( '-{', $txt );
1013 $ret = [];
1014 $first = true;
1015 foreach ( $blocks as $block ) {
1016 if ( $first ) {
1017 // Skip the part before the first -{
1018 $first = false;
1019 continue;
1020 }
1021 $mappings = explode( '}-', $block, 2 )[0];
1022 $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
1023 $table = StringUtils::explode( ';', $stripped );
1024 foreach ( $table as $t ) {
1025 $m = explode( '=>', $t, 3 );
1026 if ( count( $m ) != 2 ) {
1027 continue;
1028 }
1029 // trim any trailling comments starting with '//'
1030 $tt = explode( '//', $m[1], 2 );
1031 $ret[trim( $m[0] )] = trim( $tt[0] );
1032 }
1033 }
1034
1035 // recursively parse the subpages
1036 if ( $recursive ) {
1037 foreach ( $sublinks as $link ) {
1038 $s = $this->parseCachedTable( $code, $link, $recursive );
1039 $ret = $s + $ret;
1040 }
1041 }
1042
1043 if ( $this->mUcfirst ) {
1044 foreach ( $ret as $k => $v ) {
1045 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
1046 }
1047 }
1048 return $ret;
1049 }
1050
1051 /**
1052 * Enclose a string with the "no conversion" tag. This is used by
1053 * various functions in the Parser.
1054 *
1055 * @param string $text Text to be tagged for no conversion
1056 * @param bool $noParse Unused
1057 * @return string The tagged text
1058 */
1059 public function markNoConversion( $text, $noParse = false ) {
1060 # don't mark if already marked
1061 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
1062 return $text;
1063 }
1064
1065 $ret = "-{R|$text}-";
1066 return $ret;
1067 }
1068
1069 /**
1070 * Convert the sorting key for category links. This should make different
1071 * keys that are variants of each other map to the same key.
1072 *
1073 * @param string $key
1074 *
1075 * @return string
1076 */
1077 function convertCategoryKey( $key ) {
1078 return $key;
1079 }
1080
1081 /**
1082 * Refresh the cache of conversion tables when
1083 * MediaWiki:Conversiontable* is updated.
1084 *
1085 * @param Title $titleobj The Title of the page being updated
1086 */
1087 public function updateConversionTable( Title $titleobj ) {
1088 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
1089 $title = $titleobj->getDBkey();
1090 $t = explode( '/', $title, 3 );
1091 $c = count( $t );
1092 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1093 if ( $this->validateVariant( $t[1] ) ) {
1094 $this->reloadTables();
1095 }
1096 }
1097 }
1098 }
1099
1100 /**
1101 * Get the cached separator pattern for ConverterRule::parseRules()
1102 * @return string
1103 */
1104 function getVarSeparatorPattern() {
1105 if ( is_null( $this->mVarSeparatorPattern ) ) {
1106 // varsep_pattern for preg_split:
1107 // text should be splited by ";" only if a valid variant
1108 // name exist after the markup, for example:
1109 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1110 // <span style="font-size:120%;">yyy</span>;}-
1111 // we should split it as:
1112 // [
1113 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1114 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1115 // [2] => ''
1116 // ]
1117 $pat = '/;\s*(?=';
1118 foreach ( $this->mVariants as $variant ) {
1119 // zh-hans:xxx;zh-hant:yyy
1120 $pat .= $variant . '\s*:|';
1121 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1122 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1123 }
1124 $pat .= '\s*$)/';
1125 $this->mVarSeparatorPattern = $pat;
1126 }
1127 return $this->mVarSeparatorPattern;
1128 }
1129 }