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