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