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