MediaWiki  master
LanguageConverter.php
Go to the documentation of this file.
1 <?php
29 
35 abstract class LanguageConverter implements ILanguageConverter {
37 
43  public static $languagesWithVariants = [
44  'ban',
45  'en',
46  'crh',
47  'gan',
48  'iu',
49  'kk',
50  'ku',
51  'shi',
52  'sr',
53  'tg',
54  'uz',
55  'zh',
56  ];
57 
59 
63  public $mVariants;
66  private $mTablesLoaded = false;
67 
71  protected $mTables;
72 
74  public $mManualLevel;
75 
79  private $mLangObj;
80  public $mFlags;
81  public $mDescCodeSep = ':';
82  public $mDescVarSep = ';';
83  private $mUcfirst = false;
84  private $mConvRuleTitle = false;
85  private $mURLVariant;
86  private $mUserVariant;
87  private $mHeaderVariant;
88  private $mMaxDepth = 10;
90 
91  private const CACHE_VERSION_KEY = 'VERSION 7';
92 
101  public function __construct(
102  $langobj,
103  $maincode,
104  $variants = [],
105  $variantfallbacks = [],
106  $flags = [],
107  $manualLevel = []
108  ) {
109  global $wgDisabledVariants;
110 
111  $this->deprecatePublicProperty( 'mURLVariant', '1.35', __CLASS__ );
112  $this->deprecatePublicProperty( 'mUcfirst', '1.35', __CLASS__ );
113  $this->deprecatePublicProperty( 'mConvRuleTitle', '1.35', __CLASS__ );
114  $this->deprecatePublicProperty( 'mUserVariant', '1.35', __CLASS__ );
115  $this->deprecatePublicProperty( 'mHeaderVariant', '1.35', __CLASS__ );
116  $this->deprecatePublicProperty( 'mMaxDepth = 10', '1.35', __CLASS__ );
117  $this->deprecatePublicProperty( 'mVarSeparatorPattern', '1.35', __CLASS__ );
118  $this->deprecatePublicProperty( 'mLangObj', '1.35', __CLASS__ );
119  $this->deprecatePublicProperty( 'mVariantFallbacks', '1.35', __CLASS__ );
120  $this->deprecatePublicProperty( 'mTablesLoaded', '1.35', __CLASS__ );
121  $this->deprecatePublicProperty( 'mTables', '1.35', __CLASS__ );
122 
123  $this->mLangObj = $langobj;
124  $this->mMainLanguageCode = $maincode;
125  $this->mVariants = array_diff( $variants, $wgDisabledVariants );
126  $this->mVariantFallbacks = $variantfallbacks;
127  $this->mVariantNames = MediaWikiServices::getInstance()
128  ->getLanguageNameUtils()
129  ->getLanguageNames();
130  $defaultflags = [
131  // 'S' show converted text
132  // '+' add rules for alltext
133  // 'E' the gave flags is error
134  // these flags above are reserved for program
135  'A' => 'A', // add rule for convert code (all text convert)
136  'T' => 'T', // title convert
137  'R' => 'R', // raw content
138  'D' => 'D', // convert description (subclass implement)
139  '-' => '-', // remove convert (not implement)
140  'H' => 'H', // add rule for convert code (but no display in placed code)
141  'N' => 'N', // current variant name
142  ];
143  $this->mFlags = array_merge( $defaultflags, $flags );
144  foreach ( $this->mVariants as $v ) {
145  if ( array_key_exists( $v, $manualLevel ) ) {
146  $this->mManualLevel[$v] = $manualLevel[$v];
147  } else {
148  $this->mManualLevel[$v] = 'bidirectional';
149  }
150  $this->mFlags[$v] = $v;
151  }
152  }
153 
160  public function getVariants() {
161  return $this->mVariants;
162  }
163 
175  public function getVariantFallbacks( $variant ) {
176  return $this->mVariantFallbacks[$variant] ?? $this->mMainLanguageCode;
177  }
178 
183  public function getConvRuleTitle() {
184  return $this->mConvRuleTitle;
185  }
186 
191  public function getPreferredVariant() {
192  global $wgDefaultLanguageVariant, $wgUser;
193 
194  $req = $this->getURLVariant();
195 
196  Hooks::runner()->onGetLangPreferredVariant( $req );
197 
198  // NOTE: For calls from Setup.php, wgUser or the session might not be set yet (T235360)
199  // Use case: During autocreation, User::isUsableName is called which uses interface
200  // messages for reserved usernames.
201  if ( $wgUser && $wgUser->isSafeToLoad() && $wgUser->isRegistered() && !$req ) {
202  $req = $this->getUserVariant( $wgUser );
203  } elseif ( !$req ) {
204  $req = $this->getHeaderVariant();
205  }
206 
207  if ( $wgDefaultLanguageVariant && !$req ) {
208  $req = $this->validateVariant( $wgDefaultLanguageVariant );
209  }
210 
211  $req = $this->validateVariant( $req );
212 
213  // This function, unlike the other get*Variant functions, is
214  // not memoized (i.e. there return value is not cached) since
215  // new information might appear during processing after this
216  // is first called.
217  if ( $req ) {
218  return $req;
219  }
221  }
222 
227  public function getDefaultVariant() {
229 
230  $req = $this->getURLVariant();
231 
232  if ( !$req ) {
233  $req = $this->getHeaderVariant();
234  }
235 
236  if ( $wgDefaultLanguageVariant && !$req ) {
237  $req = $this->validateVariant( $wgDefaultLanguageVariant );
238  }
239 
240  if ( $req ) {
241  return $req;
242  }
244  }
245 
255  public function validateVariant( $variant = null ) {
256  if ( $variant === null ) {
257  return null;
258  }
259  // Our internal variants are always lower-case; the variant we
260  // are validating may have mixed case.
261  $variant = LanguageCode::replaceDeprecatedCodes( strtolower( $variant ) );
262  if ( in_array( $variant, $this->mVariants ) ) {
263  return $variant;
264  }
265  // Browsers are supposed to use BCP 47 standard in the
266  // Accept-Language header, but not all of our internal
267  // mediawiki variant codes are BCP 47. Map BCP 47 code
268  // to our internal code.
269  foreach ( $this->mVariants as $v ) {
270  // Case-insensitive match (BCP 47 is mixed case)
271  if ( strtolower( LanguageCode::bcp47( $v ) ) === $variant ) {
272  return $v;
273  }
274  }
275  return null;
276  }
277 
283  public function getURLVariant() {
284  global $wgRequest;
285 
286  if ( $this->mURLVariant ) {
287  return $this->mURLVariant;
288  }
289 
290  // see if the preference is set in the request
291  $ret = $wgRequest->getText( 'variant' );
292 
293  if ( !$ret ) {
294  $ret = $wgRequest->getVal( 'uselang' );
295  }
296 
297  $this->mURLVariant = $this->validateVariant( $ret );
298  return $this->mURLVariant;
299  }
300 
307  protected function getUserVariant( User $user ) {
308  // This should only be called within the class after the user is known to be
309  // safe to load and logged in, but check just in case.
310  if ( !$user->isSafeToLoad() ) {
311  return false;
312  }
313 
314  if ( $user->isRegistered() ) {
315  // Get language variant preference from logged in users
316  if (
317  $this->mMainLanguageCode ==
318  MediaWikiServices::getInstance()->getContentLanguage()->getCode()
319  ) {
320  $ret = $user->getOption( 'variant' );
321  } else {
322  $ret = $user->getOption( 'variant-' . $this->mMainLanguageCode );
323  }
324  } else {
325  // figure out user lang without constructing wgLang to avoid
326  // infinite recursion
327  $ret = $user->getOption( 'language' );
328  }
329 
330  $this->mUserVariant = $this->validateVariant( $ret );
331  return $this->mUserVariant;
332  }
333 
339  protected function getHeaderVariant() {
340  global $wgRequest;
341 
342  if ( $this->mHeaderVariant ) {
343  return $this->mHeaderVariant;
344  }
345 
346  // See if some supported language variant is set in the
347  // HTTP header.
348  $languages = array_keys( $wgRequest->getAcceptLang() );
349  if ( empty( $languages ) ) {
350  return null;
351  }
352 
353  $fallbackLanguages = [];
354  foreach ( $languages as $language ) {
355  $this->mHeaderVariant = $this->validateVariant( $language );
356  if ( $this->mHeaderVariant ) {
357  break;
358  }
359 
360  // To see if there are fallbacks of current language.
361  // We record these fallback variants, and process
362  // them later.
363  $fallbacks = $this->getVariantFallbacks( $language );
364  if ( is_string( $fallbacks ) && $fallbacks !== $this->mMainLanguageCode ) {
365  $fallbackLanguages[] = $fallbacks;
366  } elseif ( is_array( $fallbacks ) ) {
367  $fallbackLanguages =
368  array_merge( $fallbackLanguages, $fallbacks );
369  }
370  }
371 
372  if ( !$this->mHeaderVariant ) {
373  // process fallback languages now
374  $fallback_languages = array_unique( $fallbackLanguages );
375  foreach ( $fallback_languages as $language ) {
376  $this->mHeaderVariant = $this->validateVariant( $language );
377  if ( $this->mHeaderVariant ) {
378  break;
379  }
380  }
381  }
382 
383  return $this->mHeaderVariant;
384  }
385 
396  public function autoConvert( $text, $toVariant = false ) {
397  $this->loadTables();
398 
399  if ( !$toVariant ) {
400  $toVariant = $this->getPreferredVariant();
401  if ( !$toVariant ) {
402  return $text;
403  }
404  }
405 
406  if ( $this->guessVariant( $text, $toVariant ) ) {
407  return $text;
408  }
409  /* we convert everything except:
410  1. HTML markups (anything between < and >)
411  2. HTML entities
412  3. placeholders created by the parser
413  IMPORTANT: Beware of failure from pcre.backtrack_limit (T124404).
414  Minimize use of backtracking where possible.
415  */
416  static $reg;
417  if ( $reg === null ) {
418  $marker = '|' . Parser::MARKER_PREFIX . '[^\x7f]++\x7f';
419 
420  // this one is needed when the text is inside an HTML markup
421  $htmlfix = '|<[^>\004]++(?=\004$)|^[^<>]*+>';
422 
423  // Optimize for the common case where these tags have
424  // few or no children. Thus try and possesively get as much as
425  // possible, and only engage in backtracking when we hit a '<'.
426 
427  // disable convert to variants between <code> tags
428  $codefix = '<code>[^<]*+(?:(?:(?!<\/code>).)[^<]*+)*+<\/code>|';
429  // disable conversion of <script> tags
430  $scriptfix = '<script[^>]*+>[^<]*+(?:(?:(?!<\/script>).)[^<]*+)*+<\/script>|';
431  // disable conversion of <pre> tags
432  $prefix = '<pre[^>]*+>[^<]*+(?:(?:(?!<\/pre>).)[^<]*+)*+<\/pre>|';
433  // The "|.*+)" at the end, is in case we missed some part of html syntax,
434  // we will fail securely (hopefully) by matching the rest of the string.
435  $htmlFullTag = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)|';
436 
437  $reg = '/' . $codefix . $scriptfix . $prefix . $htmlFullTag .
438  '&[a-zA-Z#][a-z0-9]++;' . $marker . $htmlfix . '|\004$/s';
439  }
440  $startPos = 0;
441  $sourceBlob = '';
442  $literalBlob = '';
443 
444  // Guard against delimiter nulls in the input
445  // (should never happen: see T159174)
446  $text = str_replace( "\000", '', $text );
447  $text = str_replace( "\004", '', $text );
448 
449  $markupMatches = null;
450  $elementMatches = null;
451 
452  // We add a marker (\004) at the end of text, to ensure we always match the
453  // entire text (Otherwise, pcre.backtrack_limit might cause silent failure)
454  $textWithMarker = $text . "\004";
455  while ( $startPos < strlen( $text ) ) {
456  if ( preg_match( $reg, $textWithMarker, $markupMatches, PREG_OFFSET_CAPTURE, $startPos ) ) {
457  $elementPos = $markupMatches[0][1];
458  $element = $markupMatches[0][0];
459  if ( $element === "\004" ) {
460  // We hit the end.
461  $elementPos = strlen( $text );
462  $element = '';
463  } elseif ( substr( $element, -1 ) === "\004" ) {
464  // This can sometimes happen if we have
465  // unclosed html tags (For example
466  // when converting a title attribute
467  // during a recursive call that contains
468  // a &lt; e.g. <div title="&lt;">.
469  $element = substr( $element, 0, -1 );
470  }
471  } else {
472  // If we hit here, then Language Converter could be tricked
473  // into doing an XSS, so we refuse to translate.
474  // If non-crazy input manages to reach this code path,
475  // we should consider it a bug.
476  $log = LoggerFactory::getInstance( 'languageconverter' );
477  $log->error( "Hit pcre.backtrack_limit in " . __METHOD__
478  . ". Disabling language conversion for this page.",
479  [
480  "method" => __METHOD__,
481  "variant" => $toVariant,
482  "startOfText" => substr( $text, 0, 500 )
483  ]
484  );
485  return $text;
486  }
487  // Queue the part before the markup for translation in a batch
488  $sourceBlob .= substr( $text, $startPos, $elementPos - $startPos ) . "\000";
489 
490  // Advance to the next position
491  $startPos = $elementPos + strlen( $element );
492 
493  // Translate any alt or title attributes inside the matched element
494  if ( $element !== ''
495  && preg_match( '/^(<[^>\s]*+)\s([^>]*+)(.*+)$/', $element, $elementMatches )
496  ) {
497  // FIXME, this decodes entities, so if you have something
498  // like <div title="foo&lt;bar"> the bar won't get
499  // translated since after entity decoding it looks like
500  // unclosed html and we call this method recursively
501  // on attributes.
502  $attrs = Sanitizer::decodeTagAttributes( $elementMatches[2] );
503  // Ensure self-closing tags stay self-closing.
504  $close = substr( $elementMatches[2], -1 ) === '/' ? ' /' : '';
505  $changed = false;
506  foreach ( [ 'title', 'alt' ] as $attrName ) {
507  if ( !isset( $attrs[$attrName] ) ) {
508  continue;
509  }
510  $attr = $attrs[$attrName];
511  // Don't convert URLs
512  if ( !strpos( $attr, '://' ) ) {
513  $attr = $this->recursiveConvertTopLevel( $attr, $toVariant );
514  }
515 
516  if ( $attr !== $attrs[$attrName] ) {
517  $attrs[$attrName] = $attr;
518  $changed = true;
519  }
520  }
521  if ( $changed ) {
522  // @phan-suppress-next-line SecurityCheck-DoubleEscaped Explained above with decodeTagAttributes
523  $element = $elementMatches[1] . Html::expandAttributes( $attrs ) .
524  $close . $elementMatches[3];
525  }
526  }
527  $literalBlob .= $element . "\000";
528  }
529 
530  // Do the main translation batch
531  $translatedBlob = $this->translate( $sourceBlob, $toVariant );
532 
533  // Put the output back together
534  $translatedIter = StringUtils::explode( "\000", $translatedBlob );
535  $literalIter = StringUtils::explode( "\000", $literalBlob );
536  $output = '';
537  while ( $translatedIter->valid() && $literalIter->valid() ) {
538  $output .= $translatedIter->current();
539  $output .= $literalIter->current();
540  $translatedIter->next();
541  $literalIter->next();
542  }
543 
544  return $output;
545  }
546 
556  public function translate( $text, $variant ) {
557  // If $text is empty or only includes spaces, do nothing
558  // Otherwise translate it
559  if ( trim( $text ) ) {
560  $this->loadTables();
561  $text = $this->mTables[$variant]->replace( $text );
562  }
563  return $text;
564  }
565 
572  public function autoConvertToAllVariants( $text ) {
573  $this->loadTables();
574 
575  $ret = [];
576  foreach ( $this->mVariants as $variant ) {
577  $ret[$variant] = $this->translate( $text, $variant );
578  }
579 
580  return $ret;
581  }
582 
588  protected function applyManualConv( ConverterRule $convRule ) {
589  // Use syntax -{T|zh-cn:TitleCN; zh-tw:TitleTw}- to custom
590  // title conversion.
591  // T26072: $mConvRuleTitle was overwritten by other manual
592  // rule(s) not for title, this breaks the title conversion.
593  $newConvRuleTitle = $convRule->getTitle();
594  if ( $newConvRuleTitle ) {
595  // So I add an empty check for getTitle()
596  $this->mConvRuleTitle = $newConvRuleTitle;
597  }
598 
599  // merge/remove manual conversion rules to/from global table
600  $convTable = $convRule->getConvTable();
601  $action = $convRule->getRulesAction();
602  foreach ( $convTable as $variant => $pair ) {
603  $v = $this->validateVariant( $variant );
604  if ( !$v ) {
605  continue;
606  }
607 
608  if ( $action == 'add' ) {
609  // More efficient than array_merge(), about 2.5 times.
610  foreach ( $pair as $from => $to ) {
611  $this->mTables[$v]->setPair( $from, $to );
612  }
613  } elseif ( $action == 'remove' ) {
614  $this->mTables[$v]->removeArray( $pair );
615  }
616  }
617  }
618 
626  public function convertTitle( LinkTarget $linkTarget ) {
627  $variant = $this->getPreferredVariant();
628  $index = $linkTarget->getNamespace();
629  if ( $index !== NS_MAIN ) {
630  $text = $this->convertNamespace( $index, $variant ) . ':';
631  } else {
632  $text = '';
633  }
634  $text .= $this->translate( $linkTarget->getText(), $variant );
635 
636  return $text;
637  }
638 
646  public function convertNamespace( $index, $variant = null ) {
647  if ( $index === NS_MAIN ) {
648  return '';
649  }
650 
651  if ( $variant === null ) {
652  $variant = $this->getPreferredVariant();
653  }
654 
655  $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
656  $key = $cache->makeKey( 'languageconverter', 'namespace-text', $index, $variant );
657  $nsVariantText = $cache->get( $key );
658  if ( $nsVariantText !== false ) {
659  return $nsVariantText;
660  }
661 
662  // First check if a message gives a converted name in the target variant.
663  $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inLanguage( $variant );
664  if ( $nsConvMsg->exists() ) {
665  $nsVariantText = $nsConvMsg->plain();
666  }
667 
668  // Then check if a message gives a converted name in content language
669  // which needs extra translation to the target variant.
670  if ( $nsVariantText === false ) {
671  $nsConvMsg = wfMessage( 'conversion-ns' . $index )->inContentLanguage();
672  if ( $nsConvMsg->exists() ) {
673  $nsVariantText = $this->translate( $nsConvMsg->plain(), $variant );
674  }
675  }
676 
677  if ( $nsVariantText === false ) {
678  // No message exists, retrieve it from the target variant's namespace names.
679  $mLangObj = MediaWikiServices::getInstance()
680  ->getLanguageFactory()
681  ->getLanguage( $variant );
682  $nsVariantText = $mLangObj->getFormattedNsText( $index );
683  }
684 
685  $cache->set( $key, $nsVariantText, 60 );
686 
687  return $nsVariantText;
688  }
689 
708  public function convert( $text ) {
709  $variant = $this->getPreferredVariant();
710  return $this->convertTo( $text, $variant );
711  }
712 
722  public function convertTo( $text, $variant ) {
723  $languageConverterFactory = MediaWikiServices::getInstance()->getLanguageConverterFactory();
724  if ( $languageConverterFactory->isConversionDisabled() ) {
725  return $text;
726  }
727  // Reset converter state for a new converter run.
728  $this->mConvRuleTitle = false;
729  return $this->recursiveConvertTopLevel( $text, $variant );
730  }
731 
741  protected function recursiveConvertTopLevel( $text, $variant, $depth = 0 ) {
742  $startPos = 0;
743  $out = '';
744  $length = strlen( $text );
745  $shouldConvert = !$this->guessVariant( $text, $variant );
746  $continue = true;
747 
748  $noScript = '<script.*?>.*?<\/script>(*SKIP)(*FAIL)';
749  $noStyle = '<style.*?>.*?<\/style>(*SKIP)(*FAIL)';
750  // phpcs:ignore Generic.Files.LineLength
751  $noHtml = '<(?:[^>=]*+(?>[^>=]*+=\s*+(?:"[^"]*"|\'[^\']*\'|[^\'">\s]*+))*+[^>=]*+>|.*+)(*SKIP)(*FAIL)';
752  while ( $startPos < $length && $continue ) {
753  $continue = preg_match(
754  // Only match -{ outside of html.
755  "/$noScript|$noStyle|$noHtml|-\{/",
756  $text,
757  $m,
758  PREG_OFFSET_CAPTURE,
759  $startPos
760  );
761 
762  if ( !$continue ) {
763  // No more markup, append final segment
764  $fragment = substr( $text, $startPos );
765  $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
766  return $out;
767  }
768 
769  // Offset of the match of the regex pattern.
770  $pos = $m[0][1];
771 
772  // Append initial segment
773  $fragment = substr( $text, $startPos, $pos - $startPos );
774  $out .= $shouldConvert ? $this->autoConvert( $fragment, $variant ) : $fragment;
775  // -{ marker found, not in attribute
776  // Advance position up to -{ marker.
777  $startPos = $pos;
778  // Do recursive conversion
779  // Note: This passes $startPos by reference, and advances it.
780  $out .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
781  }
782  return $out;
783  }
784 
796  protected function recursiveConvertRule( $text, $variant, &$startPos, $depth = 0 ) {
797  // Quick sanity check (no function calls)
798  if ( $text[$startPos] !== '-' || $text[$startPos + 1] !== '{' ) {
799  throw new MWException( __METHOD__ . ': invalid input string' );
800  }
801 
802  $startPos += 2;
803  $inner = '';
804  $warningDone = false;
805  $length = strlen( $text );
806 
807  while ( $startPos < $length ) {
808  $m = false;
809  preg_match( '/-\{|\}-/', $text, $m, PREG_OFFSET_CAPTURE, $startPos );
810  if ( !$m ) {
811  // Unclosed rule
812  break;
813  }
814 
815  $token = $m[0][0];
816  $pos = $m[0][1];
817 
818  // Markup found
819  // Append initial segment
820  $inner .= substr( $text, $startPos, $pos - $startPos );
821 
822  // Advance position
823  $startPos = $pos;
824 
825  switch ( $token ) {
826  case '-{':
827  // Check max depth
828  if ( $depth >= $this->mMaxDepth ) {
829  $inner .= '-{';
830  if ( !$warningDone ) {
831  $inner .= '<span class="error">' .
832  wfMessage( 'language-converter-depth-warning' )
833  ->numParams( $this->mMaxDepth )->inContentLanguage()->text() .
834  '</span>';
835  $warningDone = true;
836  }
837  $startPos += 2;
838  break;
839  }
840  // Recursively parse another rule
841  $inner .= $this->recursiveConvertRule( $text, $variant, $startPos, $depth + 1 );
842  break;
843  case '}-':
844  // Apply the rule
845  $startPos += 2;
846  $rule = new ConverterRule( $inner, $this );
847  $rule->parse( $variant );
848  $this->applyManualConv( $rule );
849  return $rule->getDisplay();
850  default:
851  throw new MWException( __METHOD__ . ': invalid regex match' );
852  }
853  }
854 
855  // Unclosed rule
856  if ( $startPos < $length ) {
857  $inner .= substr( $text, $startPos );
858  }
859  $startPos = $length;
860  return '-{' . $this->autoConvert( $inner, $variant );
861  }
862 
874  public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
875  # If the article has already existed, there is no need to
876  # check it again, otherwise it may cause a fault.
877  if ( is_object( $nt ) && $nt->exists() ) {
878  return;
879  }
880 
881  global $wgRequest;
882  $isredir = $wgRequest->getText( 'redirect', 'yes' );
883  $action = $wgRequest->getText( 'action' );
884  if ( $action == 'edit' && $wgRequest->getBool( 'redlink' ) ) {
885  $action = 'view';
886  }
887  $linkconvert = $wgRequest->getText( 'linkconvert', 'yes' );
888  $disableLinkConversion =
889  MediaWikiServices::getInstance()->getLanguageConverterFactory()
890  ->isLinkConversionDisabled();
891  $linkBatchFactory = MediaWikiServices::getInstance()->getLinkBatchFactory();
892  $linkBatch = $linkBatchFactory->newLinkBatch();
893 
894  $ns = NS_MAIN;
895 
896  if ( $disableLinkConversion ||
897  ( !$ignoreOtherCond &&
898  ( $isredir == 'no'
899  || $action == 'edit'
900  || $action == 'submit'
901  || $linkconvert == 'no' ) ) ) {
902  return;
903  }
904 
905  if ( is_object( $nt ) ) {
906  $ns = $nt->getNamespace();
907  }
908 
909  $variants = $this->autoConvertToAllVariants( $link );
910  if ( !$variants ) { // give up
911  return;
912  }
913 
914  $titles = [];
915 
916  foreach ( $variants as $v ) {
917  if ( $v != $link ) {
918  $varnt = Title::newFromText( $v, $ns );
919  if ( $varnt !== null ) {
920  $linkBatch->addObj( $varnt );
921  $titles[] = $varnt;
922  }
923  }
924  }
925 
926  // fetch all variants in single query
927  $linkBatch->execute();
928 
929  foreach ( $titles as $varnt ) {
930  if ( $varnt->getArticleID() > 0 ) {
931  $nt = $varnt;
932  $link = $varnt->getText();
933  break;
934  }
935  }
936  }
937 
943  public function getExtraHashOptions() {
944  $variant = $this->getPreferredVariant();
945 
946  return '!' . $variant;
947  }
948 
959  public function guessVariant( $text, $variant ) {
960  return false;
961  }
962 
969  protected function loadDefaultTables() {
970  $class = static::class;
971  throw new MWException( "Must implement loadDefaultTables() method in class $class" );
972  }
973 
979  protected function loadTables( $fromCache = true ) {
981 
982  if ( $this->mTablesLoaded ) {
983  return;
984  }
985 
986  $this->mTablesLoaded = true;
987  // Do not use null as starting value, as that would confuse phan a lot.
988  $this->mTables = [];
990  $cacheKey = $cache->makeKey( 'conversiontables', $this->mMainLanguageCode );
991  if ( $fromCache ) {
992  $this->mTables = $cache->get( $cacheKey );
993  }
994  if ( !$this->mTables || !array_key_exists( self::CACHE_VERSION_KEY, $this->mTables ) ) {
995  // not in cache, or we need a fresh reload.
996  // We will first load the default tables
997  // then update them using things in MediaWiki:Conversiontable/*
998  $this->loadDefaultTables();
999  foreach ( $this->mVariants as $var ) {
1000  $cached = $this->parseCachedTable( $var );
1001  // @phan-suppress-next-next-line PhanTypeArraySuspiciousNullable
1002  // FIXME: $this->mTables could theoretically be null here
1003  $this->mTables[$var]->mergeArray( $cached );
1004  }
1005 
1006  $this->postLoadTables();
1007  $this->mTables[self::CACHE_VERSION_KEY] = true;
1008 
1009  $cache->set( $cacheKey, $this->mTables, 43200 );
1010  }
1011  }
1012 
1016  protected function postLoadTables() {
1017  }
1018 
1026  private function reloadTables() {
1027  if ( $this->mTables ) {
1028  // @phan-suppress-next-line PhanTypeObjectUnsetDeclaredProperty
1029  unset( $this->mTables );
1030  }
1031 
1032  $this->mTablesLoaded = false;
1033  $this->loadTables( false );
1034  }
1035 
1055  private function parseCachedTable( $code, $subpage = '', $recursive = true ) {
1056  static $parsed = [];
1057 
1058  $key = 'Conversiontable/' . $code;
1059  if ( $subpage ) {
1060  $key .= '/' . $subpage;
1061  }
1062  if ( array_key_exists( $key, $parsed ) ) {
1063  return [];
1064  }
1065 
1066  $parsed[$key] = true;
1067 
1068  if ( $subpage === '' ) {
1069  $messageCache = MediaWikiServices::getInstance()->getMessageCache();
1070  $txt = $messageCache->getMsgFromNamespace( $key, $code );
1071  } else {
1072  $txt = false;
1074  if ( $title && $title->exists() ) {
1075  $revision = MediaWikiServices::getInstance()
1076  ->getRevisionLookup()
1077  ->getRevisionByTitle( $title );
1078  if ( $revision ) {
1079  $model = $revision->getSlot(
1080  SlotRecord::MAIN,
1081  RevisionRecord::RAW
1082  )->getModel();
1083  if ( $model == CONTENT_MODEL_WIKITEXT ) {
1084  // @phan-suppress-next-line PhanUndeclaredMethod
1085  $txt = $revision->getContent(
1086  SlotRecord::MAIN,
1087  RevisionRecord::RAW
1088  )->getText();
1089  }
1090 
1091  // @todo in the future, use a specialized content model, perhaps based on json!
1092  }
1093  }
1094  }
1095 
1096  # Nothing to parse if there's no text
1097  if ( $txt === false || $txt === null || $txt === '' ) {
1098  return [];
1099  }
1100 
1101  // get all subpage links of the form
1102  // [[MediaWiki:Conversiontable/zh-xx/...|...]]
1103  $linkhead = $this->mLangObj->getNsText( NS_MEDIAWIKI ) .
1104  ':Conversiontable';
1105  $subs = StringUtils::explode( '[[', $txt );
1106  $sublinks = [];
1107  foreach ( $subs as $sub ) {
1108  $link = explode( ']]', $sub, 2 );
1109  if ( count( $link ) != 2 ) {
1110  continue;
1111  }
1112  $b = explode( '|', $link[0], 2 );
1113  $b = explode( '/', trim( $b[0] ), 3 );
1114  if ( count( $b ) == 3 ) {
1115  $sublink = $b[2];
1116  } else {
1117  $sublink = '';
1118  }
1119 
1120  if ( $b[0] == $linkhead && $b[1] == $code ) {
1121  $sublinks[] = $sublink;
1122  }
1123  }
1124 
1125  // parse the mappings in this page
1126  $blocks = StringUtils::explode( '-{', $txt );
1127  $ret = [];
1128  $first = true;
1129  foreach ( $blocks as $block ) {
1130  if ( $first ) {
1131  // Skip the part before the first -{
1132  $first = false;
1133  continue;
1134  }
1135  $mappings = explode( '}-', $block, 2 )[0];
1136  $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
1137  $table = StringUtils::explode( ';', $stripped );
1138  foreach ( $table as $t ) {
1139  $m = explode( '=>', $t, 3 );
1140  if ( count( $m ) != 2 ) {
1141  continue;
1142  }
1143  // trim any trailling comments starting with '//'
1144  $tt = explode( '//', $m[1], 2 );
1145  $ret[trim( $m[0] )] = trim( $tt[0] );
1146  }
1147  }
1148 
1149  // recursively parse the subpages
1150  if ( $recursive ) {
1151  foreach ( $sublinks as $link ) {
1152  $s = $this->parseCachedTable( $code, $link, $recursive );
1153  $ret = $s + $ret;
1154  }
1155  }
1156 
1157  if ( $this->mUcfirst ) {
1158  foreach ( $ret as $k => $v ) {
1159  $ret[$this->mLangObj->ucfirst( $k )] = $this->mLangObj->ucfirst( $v );
1160  }
1161  }
1162  return $ret;
1163  }
1164 
1173  public function markNoConversion( $text, $noParse = false ) {
1174  # don't mark if already marked
1175  if ( strpos( $text, '-{' ) || strpos( $text, '}-' ) ) {
1176  return $text;
1177  }
1178 
1179  $ret = "-{R|$text}-";
1180  return $ret;
1181  }
1182 
1191  public function convertCategoryKey( $key ) {
1192  return $key;
1193  }
1194 
1201  public function updateConversionTable( LinkTarget $linkTarget ) {
1202  if ( $linkTarget->getNamespace() === NS_MEDIAWIKI ) {
1203  $t = explode( '/', $linkTarget->getDBkey(), 3 );
1204  $c = count( $t );
1205  if ( $c > 1 && $t[0] == 'Conversiontable' ) {
1206  if ( $this->validateVariant( $t[1] ) ) {
1207  $this->reloadTables();
1208  }
1209  }
1210  }
1211  }
1212 
1217  public function getVarSeparatorPattern() {
1218  if ( $this->mVarSeparatorPattern === null ) {
1219  // varsep_pattern for preg_split:
1220  // text should be splited by ";" only if a valid variant
1221  // name exist after the markup, for example:
1222  // -{zh-hans:<span style="font-size:120%;">xxx</span>;zh-hant:\
1223  // <span style="font-size:120%;">yyy</span>;}-
1224  // we should split it as:
1225  // [
1226  // [0] => 'zh-hans:<span style="font-size:120%;">xxx</span>'
1227  // [1] => 'zh-hant:<span style="font-size:120%;">yyy</span>'
1228  // [2] => ''
1229  // ]
1230  $expandedVariants = [];
1231  foreach ( $this->mVariants as $variant ) {
1232  $expandedVariants[ $variant ] = 1;
1233  // Accept standard BCP 47 names for variants as well.
1234  $expandedVariants[ LanguageCode::bcp47( $variant ) ] = 1;
1235  }
1236  // Accept old deprecated names for variants
1237  foreach ( LanguageCode::getDeprecatedCodeMapping() as $old => $new ) {
1238  if ( isset( $expandedVariants[ $new ] ) ) {
1239  $expandedVariants[ $old ] = 1;
1240  }
1241  }
1242 
1243  $pat = '/;\s*(?=';
1244  foreach ( $expandedVariants as $variant => $ignore ) {
1245  // zh-hans:xxx;zh-hant:yyy
1246  $pat .= $variant . '\s*:|';
1247  // xxx=>zh-hans:yyy; xxx=>zh-hant:zzz
1248  $pat .= '[^;]*?=>\s*' . $variant . '\s*:|';
1249  }
1250  $pat .= '\s*$)/';
1251  $this->mVarSeparatorPattern = $pat;
1252  }
1254  }
1255 
1263  public function hasVariants() {
1264  return count( $this->getVariants() ) > 1;
1265  }
1266 
1277  public function hasVariant( $variant ) {
1278  return $variant && ( $variant === $this->validateVariant( $variant ) );
1279  }
1280 
1289  public function convertHtml( $text ) {
1290  // @phan-suppress-next-line SecurityCheck-DoubleEscaped convert() is documented to return html
1291  return htmlspecialchars( $this->convert( $text ) );
1292  }
1293 }
LanguageConverter\getVarSeparatorPattern
getVarSeparatorPattern()
Get the cached separator pattern for ConverterRule::parseRules()
Definition: LanguageConverter.php:1217
LanguageCode\replaceDeprecatedCodes
static replaceDeprecatedCodes( $code)
Replace deprecated language codes that were used in previous versions of MediaWiki to up-to-date,...
Definition: LanguageCode.php:161
LanguageConverter\hasVariant
hasVariant( $variant)
Strict check if the language has the specific variant.
Definition: LanguageConverter.php:1277
ConverterRule
The rules used for language conversion, this processes the rules extracted by Parser from the -{ }- w...
Definition: ConverterRule.php:28
LanguageCode\getDeprecatedCodeMapping
static getDeprecatedCodeMapping()
Returns a mapping of deprecated language codes that were used in previous versions of MediaWiki to up...
Definition: LanguageCode.php:124
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:361
LanguageConverter\$mMaxDepth
$mMaxDepth
Definition: LanguageConverter.php:88
Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:46
MediaWiki\Linker\LinkTarget\getText
getText()
Returns the link in text form, without namespace prefix or fragment.
LanguageConverter\getConvRuleTitle
getConvRuleTitle()
Get the title produced by the conversion rule.
Definition: LanguageConverter.php:183
NS_MEDIAWIKI
const NS_MEDIAWIKI
Definition: Defines.php:71
LanguageConverter\__construct
__construct( $langobj, $maincode, $variants=[], $variantfallbacks=[], $flags=[], $manualLevel=[])
Definition: LanguageConverter.php:101
$wgDisabledVariants
$wgDisabledVariants
Disabled variants array of language variant conversion.
Definition: DefaultSettings.php:3281
LanguageConverter\getExtraHashOptions
getExtraHashOptions()
Returns language specific hash options.
Definition: LanguageConverter.php:943
User\isRegistered
isRegistered()
Get whether the user is registered.
Definition: User.php:2973
LanguageConverter\CACHE_VERSION_KEY
const CACHE_VERSION_KEY
Definition: LanguageConverter.php:91
LanguageConverter\$mUcfirst
$mUcfirst
Definition: LanguageConverter.php:83
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:166
LanguageConverter\$mLangObj
Language $mLangObj
Definition: LanguageConverter.php:79
LanguageConverter\$mURLVariant
$mURLVariant
Definition: LanguageConverter.php:85
LanguageConverter\updateConversionTable
updateConversionTable(LinkTarget $linkTarget)
Refresh the cache of conversion tables when MediaWiki:Conversiontable* is updated.
Definition: LanguageConverter.php:1201
LanguageConverter\loadDefaultTables
loadDefaultTables()
Load default conversion tables.
Definition: LanguageConverter.php:969
LanguageConverter\$mConvRuleTitle
$mConvRuleTitle
Definition: LanguageConverter.php:84
LanguageConverter\$mVarSeparatorPattern
$mVarSeparatorPattern
Definition: LanguageConverter.php:89
Html\expandAttributes
static expandAttributes(array $attribs)
Given an associative array of element attributes, generate a string to stick after the element name i...
Definition: Html.php:483
LanguageConverter\$mVariants
string[] $mVariants
Definition: LanguageConverter.php:63
LanguageConverter\getURLVariant
getURLVariant()
Get the variant specified in the URL.
Definition: LanguageConverter.php:283
LanguageConverter\findVariantLink
findVariantLink(&$link, &$nt, $ignoreOtherCond=false)
If a language supports multiple variants, it is possible that non-existing link in one variant actual...
Definition: LanguageConverter.php:874
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1230
LanguageConverter\$mVariantNames
$mVariantNames
Definition: LanguageConverter.php:65
$s
$s
Definition: mergeMessageFileList.php:186
User\isSafeToLoad
isSafeToLoad()
Test if it's safe to load this User object.
Definition: User.php:308
LanguageConverter\$mTables
ReplacementArray[] bool[] $mTables
Definition: LanguageConverter.php:71
Parser\MARKER_PREFIX
const MARKER_PREFIX
Definition: Parser.php:148
LanguageConverter\$mMainLanguageCode
$mMainLanguageCode
Definition: LanguageConverter.php:58
LanguageConverter\hasVariants
hasVariants()
Check if this is a language with variants.
Definition: LanguageConverter.php:1263
LanguageConverter\$mHeaderVariant
$mHeaderVariant
Definition: LanguageConverter.php:87
NS_MAIN
const NS_MAIN
Definition: Defines.php:63
LanguageConverter\$mUserVariant
$mUserVariant
Definition: LanguageConverter.php:86
LanguageConverter\getVariantFallbacks
getVariantFallbacks( $variant)
In case some variant is not defined in the markup, we need to have some fallback.
Definition: LanguageConverter.php:175
LanguageConverter\reloadTables
reloadTables()
Reload the conversion tables.
Definition: LanguageConverter.php:1026
MediaWiki\Linker\LinkTarget\getNamespace
getNamespace()
Get the namespace index.
LanguageConverter\validateVariant
validateVariant( $variant=null)
Validate the variant and return an appropriate strict internal variant code if one exists.
Definition: LanguageConverter.php:255
MWException
MediaWiki exception.
Definition: MWException.php:29
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
LanguageConverter\getVariants
getVariants()
Get all valid variants.
Definition: LanguageConverter.php:160
$wgLanguageConverterCacheType
$wgLanguageConverterCacheType
The cache type for storing language conversion tables, which are used when parsing certain text and i...
Definition: DefaultSettings.php:2480
LanguageConverter\recursiveConvertTopLevel
recursiveConvertTopLevel( $text, $variant, $depth=0)
Recursively convert text on the outside.
Definition: LanguageConverter.php:741
$wgDefaultLanguageVariant
$wgDefaultLanguageVariant
Default variant code, if false, the default will be the language code.
Definition: DefaultSettings.php:3264
StringUtils\explode
static explode( $separator, $subject)
Workalike for explode() with limited memory usage.
Definition: StringUtils.php:326
LanguageConverter\translate
translate( $text, $variant)
Translate a string to a variant.
Definition: LanguageConverter.php:556
ObjectCache\getInstance
static getInstance( $id)
Get a cached instance of the specified type of cache object.
Definition: ObjectCache.php:78
LanguageConverter\getDefaultVariant
getDefaultVariant()
This function would not be affected by user's settings.
Definition: LanguageConverter.php:227
$title
$title
Definition: testCompression.php:38
LanguageConverter\recursiveConvertRule
recursiveConvertRule( $text, $variant, &$startPos, $depth=0)
Recursively convert text on the inside.
Definition: LanguageConverter.php:796
deprecatePublicProperty
deprecatePublicProperty( $property, $version, $class=null, $component=null)
Mark a property as deprecated.
Definition: DeprecationHelper.php:68
LanguageConverter\postLoadTables
postLoadTables()
Hook for post processing after conversion tables are loaded.
Definition: LanguageConverter.php:1016
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:650
LanguageConverter\$mTablesLoaded
$mTablesLoaded
Definition: LanguageConverter.php:66
ReplacementArray
Wrapper around strtr() that holds replacements.
Definition: ReplacementArray.php:24
ILanguageConverter
The shared interface for all language converters.
Definition: ILanguageConverter.php:28
ConverterRule\getConvTable
getConvTable()
Get conversion table.
Definition: ConverterRule.php:492
LanguageConverter\$mManualLevel
string[] $mManualLevel
One of 'bidirectional' 'unidirectional' 'disable' for each variant.
Definition: LanguageConverter.php:74
User\getOption
getOption( $oname, $defaultOverride=null, $ignoreHidden=false)
Get the user's current setting for a given option.
Definition: User.php:2570
LanguageConverter\convertCategoryKey
convertCategoryKey( $key)
Convert the sorting key for category links.
Definition: LanguageConverter.php:1191
LanguageConverter\parseCachedTable
parseCachedTable( $code, $subpage='', $recursive=true)
Parse the conversion table stored in the cache.
Definition: LanguageConverter.php:1055
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:172
Language\getFormattedNsText
getFormattedNsText( $index)
A convenience function that returns the same thing as getNsText() except with '_' changed to ' ',...
Definition: Language.php:681
MediaWiki\Linker\LinkTarget\getDBkey
getDBkey()
Get the main part with underscores.
LanguageConverter\getPreferredVariant
getPreferredVariant()
Get preferred language variant.
Definition: LanguageConverter.php:191
LanguageConverter\markNoConversion
markNoConversion( $text, $noParse=false)
Enclose a string with the "no conversion" tag.
Definition: LanguageConverter.php:1173
LanguageConverter\autoConvert
autoConvert( $text, $toVariant=false)
Dictionary-based conversion.
Definition: LanguageConverter.php:396
LanguageConverter\$mDescCodeSep
$mDescCodeSep
Definition: LanguageConverter.php:81
CONTENT_MODEL_WIKITEXT
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:218
LanguageConverter\convert
convert( $text)
Convert text to different variants of a language.
Definition: LanguageConverter.php:708
LanguageConverter\loadTables
loadTables( $fromCache=true)
Load conversion tables either from the cache or the disk.
Definition: LanguageConverter.php:979
LanguageConverter\getUserVariant
getUserVariant(User $user)
Determine if the user has a variant set.
Definition: LanguageConverter.php:307
LanguageConverter\$mFlags
$mFlags
Definition: LanguageConverter.php:80
LanguageConverter\$languagesWithVariants
static array $languagesWithVariants
languages supporting variants
Definition: LanguageConverter.php:43
ConverterRule\getRulesAction
getRulesAction()
Return how deal with conversion rules.
Definition: ConverterRule.php:483
$cache
$cache
Definition: mcc.php:33
LanguageCode\bcp47
static bcp47( $code)
Get the normalised IETF language tag See unit test for examples.
Definition: LanguageCode.php:175
LanguageConverter\$mDescVarSep
$mDescVarSep
Definition: LanguageConverter.php:82
LanguageConverter\convertTitle
convertTitle(LinkTarget $linkTarget)
Auto convert a LinkTarget object to a readable string in the preferred variant.
Definition: LanguageConverter.php:626
LanguageConverter\applyManualConv
applyManualConv(ConverterRule $convRule)
Apply manual conversion rules.
Definition: LanguageConverter.php:588
LanguageConverter\autoConvertToAllVariants
autoConvertToAllVariants( $text)
Call translate() to convert text to all valid variants.
Definition: LanguageConverter.php:572
Sanitizer\decodeTagAttributes
static decodeTagAttributes( $text)
Return an associative array of attribute names and values from a partial tag string.
Definition: Sanitizer.php:1008
LanguageConverter\convertTo
convertTo( $text, $variant)
Same as convert() except a extra parameter to custom variant.
Definition: LanguageConverter.php:722
$t
$t
Definition: testCompression.php:74
LanguageConverter\getHeaderVariant
getHeaderVariant()
Determine the language variant from the Accept-Language header.
Definition: LanguageConverter.php:339
$wgRequest
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:645
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
DeprecationHelper
trait DeprecationHelper
Use this trait in classes which have properties for which public access is deprecated.
Definition: DeprecationHelper.php:45
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:56
LanguageConverter\guessVariant
guessVariant( $text, $variant)
Guess if a text is written in a variant.
Definition: LanguageConverter.php:959
LanguageConverter\$mVariantFallbacks
$mVariantFallbacks
Definition: LanguageConverter.php:64
LanguageConverter
Base class for multi-variant language conversion.
Definition: LanguageConverter.php:35
ConverterRule\getTitle
getTitle()
Get converted title.
Definition: ConverterRule.php:475
LanguageConverter\convertHtml
convertHtml( $text)
Perform output conversion on a string, and encode for safe HTML output.
Definition: LanguageConverter.php:1289
LanguageConverter\convertNamespace
convertNamespace( $index, $variant=null)
Get the namespace display name in the preferred variant.
Definition: LanguageConverter.php:646
Language
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: Language.php:42
Revision\SlotRecord
Value object representing a content slot associated with a page revision.
Definition: SlotRecord.php:40