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