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