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