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