d9e64b46111ab0a2d854ae8142f40b99fa740737
[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 /**
24 * Base class for language conversion.
25 * @ingroup Language
26 *
27 * @author Zhengzhu Feng <zhengzhu@gmail.com>
28 * @author fdcn <fdcn64@gmail.com>
29 * @author shinjiman <shinjiman@gmail.com>
30 * @author PhiLiP <philip.npc@gmail.com>
31 */
32 class LanguageConverter {
33 /**
34 * languages supporting variants
35 * @since 1.20
36 * @var array
37 */
38 static public $languagesWithVariants = [
39 'en',
40 'gan',
41 'iu',
42 'kk',
43 'ku',
44 'shi',
45 'sr',
46 'tg',
47 'uz',
48 'zh',
49 ];
50
51 public $mMainLanguageCode;
52
53 /**
54 * @var string[]
55 */
56 public $mVariants;
57 public $mVariantFallbacks;
58 public $mVariantNames;
59 public $mTablesLoaded = false;
60 public $mTables;
61 // 'bidirectional' 'unidirectional' 'disable' for each variant
62 public $mManualLevel;
63
64 public $mLangObj;
65 public $mFlags;
66 public $mDescCodeSep = ':', $mDescVarSep = ';';
67 public $mUcfirst = false;
68 public $mConvRuleTitle = false;
69 public $mURLVariant;
70 public $mUserVariant;
71 public $mHeaderVariant;
72 public $mMaxDepth = 10;
73 public $mVarSeparatorPattern;
74
75 const CACHE_VERSION_KEY = 'VERSION 7';
76
77 /**
78 * @param Language $langobj
79 * @param string $maincode The main language code of this language
80 * @param string[] $variants The supported variants of this language
81 * @param array $variantfallbacks The fallback language of each variant
82 * @param array $flags Defining the custom strings that maps to the flags
83 * @param array $manualLevel Limit for supported variants
84 */
85 public function __construct( $langobj, $maincode, $variants = [],
86 $variantfallbacks = [], $flags = [],
87 $manualLevel = [] ) {
88 global $wgDisabledVariants;
89 $this->mLangObj = $langobj;
90 $this->mMainLanguageCode = $maincode;
91 $this->mVariants = array_diff( $variants, $wgDisabledVariants );
92 $this->mVariantFallbacks = $variantfallbacks;
93 $this->mVariantNames = Language::fetchLanguageNames();
94 $defaultflags = [
95 // 'S' show converted text
96 // '+' add rules for alltext
97 // 'E' the gave flags is error
98 // these flags above are reserved for program
99 'A' => 'A', // add rule for convert code (all text convert)
100 'T' => 'T', // title convert
101 'R' => 'R', // raw content
102 'D' => 'D', // convert description (subclass implement)
103 '-' => '-', // remove convert (not implement)
104 'H' => 'H', // add rule for convert code (but no display in placed code)
105 'N' => 'N', // current variant name
106 ];
107 $this->mFlags = array_merge( $defaultflags, $flags );
108 foreach ( $this->mVariants as $v ) {
109 if ( array_key_exists( $v, $manualLevel ) ) {
110 $this->mManualLevel[$v] = $manualLevel[$v];
111 } else {
112 $this->mManualLevel[$v] = 'bidirectional';
113 }
114 $this->mFlags[$v] = $v;
115 }
116 }
117
118 /**
119 * Get all valid variants.
120 * Call this instead of using $this->mVariants directly.
121 *
122 * @return string[] Contains all valid variants
123 */
124 public function getVariants() {
125 return $this->mVariants;
126 }
127
128 /**
129 * In case some variant is not defined in the markup, we need
130 * to have some fallback. For example, in zh, normally people
131 * will define zh-hans and zh-hant, but less so for zh-sg or zh-hk.
132 * when zh-sg is preferred but not defined, we will pick zh-hans
133 * in this case. Right now this is only used by zh.
134 *
135 * @param string $variant The language code of the variant
136 * @return string|array The code of the fallback language or the
137 * main code if there is no fallback
138 */
139 public function getVariantFallbacks( $variant ) {
140 if ( isset( $this->mVariantFallbacks[$variant] ) ) {
141 return $this->mVariantFallbacks[$variant];
142 }
143 return $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 // 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 */
362 $marker = '|' . Parser::MARKER_PREFIX . '[\-a-zA-Z0-9]+';
363
364 // this one is needed when the text is inside an HTML markup
365 $htmlfix = '|<[^>]+$|^[^<>]*>';
366
367 // disable convert to variants between <code> tags
368 $codefix = '<code>.+?<\/code>|';
369 // disable conversion of <script> tags
370 $scriptfix = '<script.*?>.*?<\/script>|';
371 // disable conversion of <pre> tags
372 $prefix = '<pre.*?>.*?<\/pre>|';
373
374 $reg = '/' . $codefix . $scriptfix . $prefix .
375 '<[^>]+>|&[a-zA-Z#][a-z0-9]+;' . $marker . $htmlfix . '/s';
376 $startPos = 0;
377 $sourceBlob = '';
378 $literalBlob = '';
379
380 // Guard against delimiter nulls in the input
381 // (should never happen: see T159174)
382 $text = str_replace( "\000", '', $text );
383
384 $markupMatches = null;
385 $elementMatches = null;
386 while ( $startPos < strlen( $text ) ) {
387 if ( preg_match( $reg, $text, $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
388 $elementPos = $markupMatches[0][1];
389 $element = $markupMatches[0][0];
390 } else {
391 $elementPos = strlen( $text );
392 $element = '';
393 }
394
395 // Queue the part before the markup for translation in a batch
396 $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
397
398 // Advance to the next position
399 $startPos = $elementPos + strlen( $element );
400
401 // Translate any alt or title attributes inside the matched element
402 if ( $element !== ''
403 && preg_match( '/^(<[^>\s]*)\s([^>]*)(.*)$/', $element, $elementMatches )
404 ) {
405 $attrs = Sanitizer::decodeTagAttributes( $elementMatches[2] );
406 $changed = false;
407 foreach ( [ 'title', 'alt' ] as $attrName ) {
408 if ( !isset( $attrs[$attrName] ) ) {
409 continue;
410 }
411 $attr = $attrs[$attrName];
412 // Don't convert URLs
413 if ( !strpos( $attr, '://' ) ) {
414 $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
415 }
416
417 if ( $attr !== $attrs[$attrName] ) {
418 $attrs[$attrName] = $attr;
419 $changed = true;
420 }
421 }
422 if ( $changed ) {
423 $element = $elementMatches[1] . Html::expandAttributes( $attrs ) .
424 $elementMatches[3];
425 }
426 }
427 $literalBlob .= $element . "\000";
428 }
429
430 // Do the main translation batch
431 $translatedBlob = $this->translate( $sourceBlob, $toVariant );
432
433 // Put the output back together
434 $translatedIter = StringUtils::explode( "\000", $translatedBlob );
435 $literalIter = StringUtils::explode( "\000", $literalBlob );
436 $output = '';
437 while ( $translatedIter->valid() && $literalIter->valid() ) {
438 $output .= $translatedIter->current();
439 $output .= $literalIter->current();
440 $translatedIter->next();
441 $literalIter->next();
442 }
443
444 return $output;
445 }
446
447 /**
448 * Translate a string to a variant.
449 * Doesn't parse rules or do any of that other stuff, for that use
450 * convert() or convertTo().
451 *
452 * @param string $text Text to convert
453 * @param string $variant Variant language code
454 * @return string Translated text
455 */
456 public function translate( $text, $variant ) {
457 // If $text is empty or only includes spaces, do nothing
458 // Otherwise translate it
459 if ( trim( $text ) ) {
460 $this->loadTables();
461 $text = $this->mTables[$variant]->replace( $text );
462 }
463 return $text;
464 }
465
466 /**
467 * Call translate() to convert text to all valid variants.
468 *
469 * @param string $text The text to be converted
470 * @return array Variant => converted text
471 */
472 public function autoConvertToAllVariants( $text ) {
473 $this->loadTables();
474
475 $ret = [];
476 foreach ( $this->mVariants as $variant ) {
477 $ret[$variant] = $this->translate( $text, $variant );
478 }
479
480 return $ret;
481 }
482
483 /**
484 * Apply manual conversion rules.
485 *
486 * @param ConverterRule $convRule
487 */
488 protected function applyManualConv( $convRule ) {
489 // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
490 // title conversion.
491 // T26072: $mConvRuleTitle was overwritten by other manual
492 // rule(s) not for title, this breaks the title conversion.
493 $newConvRuleTitle = $convRule->getTitle();
494 if ( $newConvRuleTitle ) {
495 // So I add an empty check for getTitle()
496 $this->mConvRuleTitle = $newConvRuleTitle;
497 }
498
499 // merge/remove manual conversion rules to/from global table
500 $convTable = $convRule->getConvTable();
501 $action = $convRule->getRulesAction();
502 foreach ( $convTable as $variant => $pair ) {
503 if ( !$this->validateVariant( $variant ) ) {
504 continue;
505 }
506
507 if ( $action == 'add' ) {
508 // More efficient than array_merge(), about 2.5 times.
509 foreach ( $pair as $from => $to ) {
510 $this->mTables[$variant]->setPair( $from, $to );
511 }
512 } elseif ( $action == 'remove' ) {
513 $this->mTables[$variant]->removeArray( $pair );
514 }
515 }
516 }
517
518 /**
519 * Auto convert a Title object to a readable string in the
520 * preferred variant.
521 *
522 * @param Title $title A object of Title
523 * @return string Converted title text
524 */
525 public function convertTitle( $title ) {
526 $variant = $this->getPreferredVariant();
527 $index = $title->getNamespace();
528 if ( $index !== NS_MAIN ) {
529 $text = $this->convertNamespace( $index, $variant ) . ':';
530 } else {
531 $text = '';
532 }
533 $text .= $this->translate( $title->getText(), $variant );
534 return $text;
535 }
536
537 /**
538 * Get the namespace display name in the preferred variant.
539 *
540 * @param int $index Namespace id
541 * @param string|null $variant Variant code or null for preferred variant
542 * @return string Namespace name for display
543 */
544 public function convertNamespace( $index, $variant = null ) {
545 if ( $index === NS_MAIN ) {
546 return '';
547 }
548
549 if ( $variant === null ) {
550 $variant = $this->getPreferredVariant();
551 }
552
553 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
554 $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
555 $nsVariantText = $cache->get( $key );
556 if ( $nsVariantText !== false ) {
557 return $nsVariantText;
558 }
559
560 // First check if a message gives a converted name in the target variant.
561 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
562 if ( $nsConvMsg->exists() ) {
563 $nsVariantText = $nsConvMsg->plain();
564 }
565
566 // Then check if a message gives a converted name in content language
567 // which needs extra translation to the target variant.
568 if ( $nsVariantText === false ) {
569 $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
570 if ( $nsConvMsg->exists() ) {
571 $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
572 }
573 }
574
575 if ( $nsVariantText === false ) {
576 // No message exists, retrieve it from the target variant's namespace names.
577 $langObj = $this->mLangObj->factory( $variant );
578 $nsVariantText = $langObj->getFormattedNsText( $index );
579 }
580
581 $cache->set( $key, $nsVariantText, 60 );
582
583 return $nsVariantText;
584 }
585
586 /**
587 * Convert text to different variants of a language. The automatic
588 * conversion is done in autoConvert(). Here we parse the text
589 * marked with -{}-, which specifies special conversions of the
590 * text that can not be accomplished in autoConvert().
591 *
592 * Syntax of the markup:
593 * -{code1:text1;code2:text2;...}- or
594 * -{flags|code1:text1;code2:text2;...}- or
595 * -{text}- in which case no conversion should take place for text
596 *
597 * @param string $text Text to be converted
598 * @return string Converted text
599 */
600 public function convert( $text ) {
601 $variant = $this->getPreferredVariant();
602 return $this->convertTo( $text, $variant );
603 }
604
605 /**
606 * Same as convert() except a extra parameter to custom variant.
607 *
608 * @param string $text Text to be converted
609 * @param string $variant The target variant code
610 * @return string Converted text
611 */
612 public function convertTo( $text, $variant ) {
613 global $wgDisableLangConversion;
614 if ( $wgDisableLangConversion ) {
615 return $text;
616 }
617 // Reset converter state for a new converter run.
618 $this->mConvRuleTitle = false;
619 return $this->recursiveConvertTopLevel( $text, $variant );
620 }
621
622 /**
623 * Recursively convert text on the outside. Allow to use nested
624 * markups to custom rules.
625 *
626 * @param string $text Text to be converted
627 * @param string $variant The target variant code
628 * @param int $depth Depth of recursion
629 * @return string Converted text
630 */
631 protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
632 $startPos = 0;
633 $out = '';
634 $length = strlen( $text );
635 $shouldConvert = !$this->guessVariant( $text, $variant );
636
637 while ( $startPos < $length ) {
638 $pos = strpos( $text, '-{', $startPos );
639
640 if ( $pos === false ) {
641 // No more markup, append final segment
642 $fragment = substr( $text, $startPos );
643 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
644 return $out;
645 }
646
647 // Markup found
648 // Append initial segment
649 $fragment = substr( $text, $startPos, $pos - $startPos );
650 $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
651
652 // Advance position
653 $startPos = $pos;
654
655 // Do recursive conversion
656 $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
657 }
658
659 return $out;
660 }
661
662 /**
663 * Recursively convert text on the inside.
664 *
665 * @param string $text Text to be converted
666 * @param string $variant The target variant code
667 * @param int $startPos
668 * @param int $depth Depth of recursion
669 *
670 * @throws MWException
671 * @return string Converted text
672 */
673 protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
674 // Quick sanity check (no function calls)
675 if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
676 throw new MWException( __METHOD__ . ': invalid input string' );
677 }
678
679 $startPos += 2;
680 $inner = '';
681 $warningDone = false;
682 $length = strlen( $text );
683
684 while ( $startPos < $length ) {
685 $m = false;
686 preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
687 if ( !$m ) {
688 // Unclosed rule
689 break;
690 }
691
692 $token = $m[0][0];
693 $pos = $m[0][1];
694
695 // Markup found
696 // Append initial segment
697 $inner .= substr( $text, $startPos, $pos - $startPos );
698
699 // Advance position
700 $startPos = $pos;
701
702 switch ( $token ) {
703 case '-{':
704 // Check max depth
705 if ( $depth >= $this->mMaxDepth ) {
706 $inner .= '-{';
707 if ( !$warningDone ) {
708 $inner .= '<span class="error">' .
709 wfMessage( 'language-converter-depth-warning' )
710 ->numParams( $this->mMaxDepth )->inContentLanguage()->text() .
711 '</span>';
712 $warningDone = true;
713 }
714 $startPos += 2;
715 continue;
716 }
717 // Recursively parse another rule
718 $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
719 break;
720 case '}-':
721 // Apply the rule
722 $startPos += 2;
723 $rule = new ConverterRule( $inner, $this );
724 $rule->parse( $variant );
725 $this->applyManualConv( $rule );
726 return $rule->getDisplay();
727 default:
728 throw new MWException( __METHOD__ . ': invalid regex match' );
729 }
730 }
731
732 // Unclosed rule
733 if ( $startPos < $length ) {
734 $inner .= substr( $text, $startPos );
735 }
736 $startPos = $length;
737 return '-{' . $this->autoConvert( $inner, $variant );
738 }
739
740 /**
741 * If a language supports multiple variants, it is possible that
742 * non-existing link in one variant actually exists in another variant.
743 * This function tries to find it. See e.g. LanguageZh.php
744 * The input parameters may be modified upon return
745 *
746 * @param string &$link The name of the link
747 * @param Title &$nt The title object of the link
748 * @param bool $ignoreOtherCond To disable other conditions when
749 * we need to transclude a template or update a category's link
750 */
751 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
752 # If the article has already existed, there is no need to
753 # check it again, otherwise it may cause a fault.
754 if ( is_object( $nt ) && $nt->exists() ) {
755 return;
756 }
757
758 global $wgDisableLangConversion, $wgDisableTitleConversion, $wgRequest;
759 $isredir = $wgRequest->getText( 'redirect', 'yes' );
760 $action = $wgRequest->getText( 'action' );
761 if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
762 $action = 'view';
763 }
764 $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
765 $disableLinkConversion = $wgDisableLangConversion
766 || $wgDisableTitleConversion;
767 $linkBatch = new LinkBatch();
768
769 $ns = NS_MAIN;
770
771 if ( $disableLinkConversion ||
772 ( !$ignoreOtherCond &&
773 ( $isredir == 'no'
774 || $action == 'edit'
775 || $action == 'submit'
776 || $linkconvert == 'no' ) ) ) {
777 return;
778 }
779
780 if ( is_object( $nt ) ) {
781 $ns = $nt->getNamespace();
782 }
783
784 $variants = $this->autoConvertToAllVariants( $link );
785 if ( !$variants ) { // give up
786 return;
787 }
788
789 $titles = [];
790
791 foreach ( $variants as $v ) {
792 if ( $v != $link ) {
793 $varnt = Title::newFromText( $v, $ns );
794 if ( !is_null( $varnt ) ) {
795 $linkBatch->addObj( $varnt );
796 $titles[] = $varnt;
797 }
798 }
799 }
800
801 // fetch all variants in single query
802 $linkBatch->execute();
803
804 foreach ( $titles as $varnt ) {
805 if ( $varnt->getArticleID() > 0 ) {
806 $nt = $varnt;
807 $link = $varnt->getText();
808 break;
809 }
810 }
811 }
812
813 /**
814 * Returns language specific hash options.
815 *
816 * @return string
817 */
818 public function getExtraHashOptions() {
819 $variant = $this->getPreferredVariant();
820
821 return '!' . $variant;
822 }
823
824 /**
825 * Guess if a text is written in a variant. This should be implemented in subclasses.
826 *
827 * @param string $text The text to be checked
828 * @param string $variant Language code of the variant to be checked for
829 * @return bool True if $text appears to be written in $variant, false if not
830 *
831 * @author Nikola Smolenski <smolensk@eunet.rs>
832 * @since 1.19
833 */
834 public function guessVariant( $text, $variant ) {
835 return false;
836 }
837
838 /**
839 * Load default conversion tables.
840 * This method must be implemented in derived class.
841 *
842 * @private
843 * @throws MWException
844 */
845 function loadDefaultTables() {
846 $class = static::class;
847 throw new MWException( "Must implement loadDefaultTables() method in class $class" );
848 }
849
850 /**
851 * Load conversion tables either from the cache or the disk.
852 * @private
853 * @param bool $fromCache Load from memcached? Defaults to true.
854 */
855 function loadTables( $fromCache = true ) {
856 global $wgLanguageConverterCacheType;
857
858 if ( $this->mTablesLoaded ) {
859 return;
860 }
861
862 $this->mTablesLoaded = true;
863 $this->mTables = false;
864 $cache = ObjectCache::getInstance( $wgLanguageConverterCacheType );
865 $cacheKey = $cache->makeKey( 'conversiontables', $this->mMainLanguageCode );
866 if ( $fromCache ) {
867 $this->mTables = $cache->get( $cacheKey );
868 }
869 if ( !$this->mTables || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
870 // not in cache, or we need a fresh reload.
871 // We will first load the default tables
872 // then update them using things in MediaWiki:Conversiontable/*
873 $this->loadDefaultTables();
874 foreach ( $this->mVariants as $var ) {
875 $cached = $this->parseCachedTable( $var );
876 $this->mTables[$var]->mergeArray( $cached );
877 }
878
879 $this->postLoadTables();
880 $this->mTables[self::CACHE_VERSION_KEY] = true;
881
882 $cache->set( $cacheKey, $this->mTables, 43200 );
883 }
884 }
885
886 /**
887 * Hook for post processing after conversion tables are loaded.
888 */
889 function postLoadTables() {
890 }
891
892 /**
893 * Reload the conversion tables.
894 *
895 * Also used by test suites which need to reset the converter state.
896 *
897 * @private
898 */
899 private function reloadTables() {
900 if ( $this->mTables ) {
901 unset( $this->mTables );
902 }
903
904 $this->mTablesLoaded = false;
905 $this->loadTables( false );
906 }
907
908 /**
909 * Parse the conversion table stored in the cache.
910 *
911 * The tables should be in blocks of the following form:
912 * -{
913 * word => word ;
914 * word => word ;
915 * ...
916 * }-
917 *
918 * To make the tables more manageable, subpages are allowed
919 * and will be parsed recursively if $recursive == true.
920 *
921 * @param string $code Language code
922 * @param string $subpage Subpage name
923 * @param bool $recursive Parse subpages recursively? Defaults to true.
924 *
925 * @return array
926 */
927 function parseCachedTable( $code, $subpage = '', $recursive = true ) {
928 static $parsed = [];
929
930 $key = 'Conversiontable/' . $code;
931 if ( $subpage ) {
932 $key .= '/' . $subpage;
933 }
934 if ( array_key_exists( $key, $parsed ) ) {
935 return [];
936 }
937
938 $parsed[$key] = true;
939
940 if ( $subpage === '' ) {
941 $txt = MessageCache::singleton()->getMsgFromNamespace( $key, $code );
942 } else {
943 $txt = false;
944 $title = Title::makeTitleSafe( NS_MEDIAWIKI, $key );
945 if ( $title && $title->exists() ) {
946 $revision = Revision::newFromTitle( $title );
947 if ( $revision ) {
948 if ( $revision->getContentModel() == CONTENT_MODEL_WIKITEXT ) {
949 $txt = $revision->getContent( Revision::RAW )->getNativeData();
950 }
951
952 // @todo in the future, use a specialized content model, perhaps based on json!
953 }
954 }
955 }
956
957 # Nothing to parse if there's no text
958 if ( $txt === false || $txt === null || $txt === '' ) {
959 return [];
960 }
961
962 // get all subpage links of the form
963 // [[MediaWiki:Conversiontable/zh-xx/...|...]]
964 $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
965 ':Conversiontable';
966 $subs = StringUtils::explode( '[[', $txt );
967 $sublinks = [];
968 foreach ( $subs as $sub ) {
969 $link = explode( ']]', $sub, 2 );
970 if ( count( $link ) != 2 ) {
971 continue;
972 }
973 $b = explode( '|', $link[0], 2 );
974 $b = explode( '/', trim( $b[0] ), 3 );
975 if ( count( $b ) == 3 ) {
976 $sublink = $b[2];
977 } else {
978 $sublink = '';
979 }
980
981 if ( $b[0] == $linkhead && $b[1] == $code ) {
982 $sublinks[] = $sublink;
983 }
984 }
985
986 // parse the mappings in this page
987 $blocks = StringUtils::explode( '-{', $txt );
988 $ret = [];
989 $first = true;
990 foreach ( $blocks as $block ) {
991 if ( $first ) {
992 // Skip the part before the first -{
993 $first = false;
994 continue;
995 }
996 $mappings = explode( '}-', $block, 2 )[0];
997 $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
998 $table = StringUtils::explode( ';', $stripped );
999 foreach ( $table as $t ) {
1000 $m = explode( '=>', $t, 3 );
1001 if ( count( $m ) != 2 ) {
1002 continue;
1003 }
1004 // trim any trailling comments starting with '//'
1005 $tt = explode( '//', $m[1], 2 );
1006 $ret[trim( $m[0] )] = trim( $tt[0] );
1007 }
1008 }
1009
1010 // recursively parse the subpages
1011 if ( $recursive ) {
1012 foreach ( $sublinks as $link ) {
1013 $s = $this->parseCachedTable( $code, $link, $recursive );
1014 $ret = $s + $ret;
1015 }
1016 }
1017
1018 if ( $this->mUcfirst ) {
1019 foreach ( $ret as $k => $v ) {
1020 $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
1021 }
1022 }
1023 return $ret;
1024 }
1025
1026 /**
1027 * Enclose a string with the "no conversion" tag. This is used by
1028 * various functions in the Parser.
1029 *
1030 * @param string $text Text to be tagged for no conversion
1031 * @param bool $noParse Unused
1032 * @return string The tagged text
1033 */
1034 public function markNoConversion( $text, $noParse = false ) {
1035 # don't mark if already marked
1036 if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
1037 return $text;
1038 }
1039
1040 $ret = "-{R|$text}-";
1041 return $ret;
1042 }
1043
1044 /**
1045 * Convert the sorting key for category links. This should make different
1046 * keys that are variants of each other map to the same key.
1047 *
1048 * @param string $key
1049 *
1050 * @return string
1051 */
1052 function convertCategoryKey( $key ) {
1053 return $key;
1054 }
1055
1056 /**
1057 * Refresh the cache of conversion tables when
1058 * MediaWiki:Conversiontable* is updated.
1059 *
1060 * @param Title $titleobj The Title of the page being updated
1061 */
1062 public function updateConversionTable( Title $titleobj ) {
1063 if ( $titleobj->getNamespace() == NS_MEDIAWIKI ) {
1064 $title = $titleobj->getDBkey();
1065 $t = explode( '/', $title, 3 );
1066 $c = count( $t );
1067 if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1068 if ( $this->validateVariant( $t[1] ) ) {
1069 $this->reloadTables();
1070 }
1071 }
1072 }
1073 }
1074
1075 /**
1076 * Get the cached separator pattern for ConverterRule::parseRules()
1077 * @return string
1078 */
1079 function getVarSeparatorPattern() {
1080 if ( is_null( $this->mVarSeparatorPattern ) ) {
1081 // varsep_pattern for preg_split:
1082 // text should be splited by ";" only if a valid variant
1083 // name exist after the markup, for example:
1084 // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1085 // <span style="font-size:120%;">yyy</span>;}-
1086 // we should split it as:
1087 // [
1088 // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1089 // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1090 // [2] => ''
1091 // ]
1092 $pat = '/;\s*(?=';
1093 foreach ( $this->mVariants as $variant ) {
1094 // zh-hans:xxx;zh-hant:yyy
1095 $pat .= $variant . '\s*:|';
1096 // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1097 $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1098 }
1099 $pat .= '\s*$)/';
1100 $this->mVarSeparatorPattern = $pat;
1101 }
1102 return $this->mVarSeparatorPattern;
1103 }
1104 }