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