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