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