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