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