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